J2ee Exception Handling specifications

Source: Internet
Author: User

Recently, with Layer-3 development, how to handle exceptions on BLL (Business Logic Layer) is confusing. Finding Relevant materials is also a bit rewarding. The following is a relatively easy-to-find document.

--------------------

Currently, J2ee projects are logically divided into multiple layers. The classic architecture is divided into three layers: presentation layer, business layer, and integration layer (including database access and external system access ).
The J2ee project has its complexity. Several issues need to be paid special attention to in exception handling of the J2ee project.
In distributed applications, we encounter many checked exceptions. All RMI calls (including remote EJB interface calls) Throw java. rmi. remoteException; at the same time, RemoteException is a checked exception. When we perform remote calls in the business system, we need to write a lot of code to handle these checked exceptions. In the event of RemoteException, these checked exceptions are very serious to the system, and there is almost no possibility of retry. That is to say, when the RemoteException and these terrible checked exceptions occur, we have no need to retry, but we have to write a lot of try... Catch code to process it. Generally, we call RMI at the bottom layer. If there is an RMI call, all upper-layer interfaces require a RemoteException. Because the RemoteException processing method is to continue to throw it. In this way, our business interfaces are damaged. RemoteException these J2EE system-level exceptions seriously affect our business interfaces. The purpose of layering the system is to reduce the dependencies between systems, and the technical changes at each layer will not affect other layers.

1 public class UserSoaImpl implements UserSoa {
2 public UserInfo getUserInfo (String userId) throws RemoteException {
3 //......
4. Remote method call.
5 //......
6}
7}
8 public interface UserManager {
9 public UserInfo getUserInfo (Stirng userId) throws RemoteException;
10}

Similarly, SQLException checked exception is thrown during JDBC access.

To avoid in-depth intrusion of system-level checked exceptions to the business system, we can define a business system exception for the business method. For very serious exceptions such as SQLException and RemoteException, we can define a new unChecked exception and then encapsulate SQLException and RemoteException into unChecked exceptions and then throw them.
If a system-level exception is to be handled by a higher-level caller, a new checked business exception can be defined, and system-level exceptions can be stored as business-level exceptions before being thrown.
Generally, we need to define an unChecked exception so that all methods of the integration layer interface can declare that this unChecked exception is thrown.

1 public DataAccessException extends RuntimeException {
2 ......
3}
4 public interface UserDao {
5 public String getPassword (String userId) throws DataAccessException;
6}
7
8 public class UserDaoImpl implements UserDAO {
9 public String getPassword (String userId) throws DataAccessException {
10 String SQL = "select password from userInfo where userId = '" + userId + "'";
11 try {
12...
13 // JDBC call
14 s.exe cuteQuery (SQL );
15...
16} catch (SQLException ex ){
17 throw new DataAccessException ("database query failed" + SQL, ex );
18}
19}
20}

Define a checked service exception so that all methods of the service layer interface declare that the Checked exception is thrown.

1 public class BusinessException extends Exception {
2 .....
3}
4
5 public interface UserManager {
6 public Userinfo copyUserInfo (Userinfo user) throws BusinessException {
7 Userinfo newUser = null;
8 try {
9 newUser = (Userinfo) user. clone ();
10} catch (CloneNotSupportedException ex ){
11 throw new BusinessException ("clone method not supported:" + Userinfo. class. getName (), ex );
12}
13}
14}

The J2ee presentation layer should be a thin layer. Its main function is to obtain page requests, assemble page parameters into POJO objects, call corresponding business methods, and then forward pages, present the corresponding business data to the page. The presentation layer needs to pay attention to one problem. The presentation layer needs to verify the validity of data. For example, some input fields cannot be empty or character length verification.
All J2ee parameters passed from the page to the backend are character-type. If you want to enter a value or a date-type parameter, you must convert the character value to the corresponding value or date value.
If the verification parameters of the Presentation Layer Code are invalid, the system should return to the original page, asking the user to reenter the data and prompt related error information.

We usually convert a parameter from the page to a value. We can see this code.

 1 ModeAndView handleRequest(HttpServletRequest request,HttpServletResponse response)throws Exception{    
2 String ageStr = request.getParameter(“age”);
3 int age = Integer.parse(ageStr);
4 …………
5
6 String birthDayStr = request.getParameter(“birthDay”);
7 SimpleDateFormat format = new SimpleDateFormat(“MM/dd/yyyy”);
8 Date birthDay = format.parse(birthDayStr);
9
10 }

The above code should be seen frequently, but when you enter a character from the page that cannot be converted to an integer or an incorrect date value.
The Integer. parse () method is throwUnChecked exception of NumberFormatException. However, this exception is definitely not a fatal exception. Generally, when the value entered by the user in the field on the page is invalid, we should prompt the user to reenter it. However, once an unchecked exception is thrown, there is no retry opportunity. Code like this causes a large amount of exception information to be displayed on the page. Make our system look very fragile.
Similarly, the SimpleDateFormat. parse () method will throwThe Checked of ParseException is abnormal..
In this case, we should all capture these unChecked exceptions and prompt the user to reenter them.

1 ModeAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws Exception {
2 String ageStr = request. getParameter ("age ");
3 String birthDayStr = request. getParameter ("birthDay ");
4 int age = 0;
5 Date birthDay = null;
6 try {
7 age = Integer. parse (ageStr );
8} catch (NumberFormatException ex ){
9 error. reject ("age", "is not a legal integer ");
10}
11 ............
12
13 try {
14 SimpleDateFormat format = new SimpleDateFormat ("MM/dd/yyyy ");
15 birthDay = format. parse (birthDayStr );
16} catch (ParseException ex ){
17 error. reject ("birthDay", "is not a legal date. Please enter a date in 'Mm/dd/yyy' format ");
18}
19
20}

In the presentation layer, it is necessary to determine whether the method to be called will throw unChecked exceptions. Under what circumstances will these exceptions be thrown and correct processing will be performed.
In the presentation layer, you can call the system's business methods without capturing exceptions. If the exception thrown by the called business method is equivalent to the second return value, capture the exception in this case.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.