Java Web Project Exception management

Source: Internet
Author: User
Tags getmessage log log

In the actual Java EE project, there will inevitably be some anomalies in the system, if the exception is allowed to print directly to the browser may make users feel puzzled, it is possible to let some users find ways to crack the system.

Come out to work for a year, I also probably have some understanding of the exception handling, in this little brother simple introduction under the personal view of the abnormal handling, I hope that the great God put forward valuable comments and suggestions.

Take the Spring+struts2+hibernate project description: Usually after a page request to the background, the first is to action (the so-called MVC Controller), the action layer will invoke the business logic service, The SERVCE layer calls the persistence layer DAO to get the data. The final execution results are aggregated to the action and then forwarded to the specified page through the action control, as shown in the following procedure:



And these three layers are actually possible anomalies, such as the DAO layer may have sqlexception,service may have nullpointexception,action may have ioexception, one but the exception and the programmer did not do the processing, Then the layer will not go down, but to call its own method throws an exception, if the DAO, Service, action layer is not handled exception, the exception information will be thrown to the server, and then the server will print the exception directly to the page, the result will be as follows:



In fact, this kind of mistake is meaningless to the customer, because they usually can't understand what it means.

When we first learned Java, we handled exceptions usually in two ways: ① direct throws, let alone, ② write Try...catch, do nothing in the catch block, or just Printstacktrace () print the exception to the console. The first method finally makes the result, and the second method is more Cup: the page does not error, but also do not execute the user's request, in short, this is actually a bug (euphemism: usually)!

So what should happen when the exception happens? I'd like to know that when you have a good understanding of Java exceptions, you should be aware that exceptions should be handled as much as possible before the action control is forwarded, log log logs, and then tell the user the error on the page with a friendly error message. Let's look at the following code:

Java code
  1. //Create log Object
  2. Log log = Logfactory.getlog (this. GetClass ());
  3.   
  4. //action layer to perform data addition operations
  5. Public String Save () {
  6. try{
  7. //Call the service's Save method
  8. service.save (obj);
  9. }catch(Exception e) {
  10. log.error (...); //Log logs   
  11. return "error"to the specified error page
  12.    }  
  13. return "Success";
  14. }  

If the exception is handled as described above, the last page that our users will see may be the following form (I think this should be a little bit friendlier):



And then we go back to the place where we just handled the anomaly, and if you accumulate some project experience, you might find it inflexible to use the above way of handling exceptions:

① because spring converts most non-runtime exceptions to run-time exceptions (runtimeexception), the programmer has no idea where try...catch should be done at all.

② Each method repeats the Try...catch, and the code in the Catch block is similar, which obviously does a lot of repetitive work and is prone to error, and also increases the number of use cases for unit tests (project managers typically prefer to estimate UT case based on line of code)

③ There are many kinds of exceptions: there may be database additions and deletions, errors may be file read and write errors, and so on. The user feels that each occurrence of an exception is an "error during the access process, please try again" does not explain the error situation, they want to make the exception information more detailed, such as: in the execution of data deletion error, so that they can more accurately provide maintenance personnel with the bug information.

How to solve the above problem? I did this: JDK exception or custom exception + exception blocker

The role of the Struts2 interceptor has a lot of information on the Internet, not to repeat here, my exception interceptor principle as shown:



First of all, my action class, service class, and DAO class if it is necessary to catch an exception, I will not log log in Try...catch,catch block, usually throw a new exception, and note the error message:

Java code
  1. //action layer to perform data addition operations
  2. Public String Save () {
  3. try{
  4. //Call the service's Save method
  5. service.save (obj);
  6. }catch(Exception e) {
  7. //You asked me why the runtime exception was thrown? Because I'm too lazy to write throws xx after the method .
  8. throw new runtimeexception ("An error occurred while adding data!  ", E);
  9.   }  
  10. return "Success";
  11. }  

The exception is then processed in the exception blocker, looking at the following code:

Java code
  1. Public String intercept (actioninvocation actioninvocation) {
  2.   
  3. String result = null; //The return value of the action   
  4. try {
  5. //Run an action that is intercepted, during which case an exception is caught
  6. result = Actioninvocation.invoke ();
  7. return result;
  8. } catch (Exception e) {
  9.             /** 
  10. * Handling Exceptions
  11.              */  
  12. String errormsg = "Unknown error!"  ";
  13. //through instanceof to determine what is the exception type
  14. if (e instanceof baseexception) {
  15. baseexception be = (baseexception) e;
  16. Be.printstacktrace (); //Print exception information during development for easy commissioning   
  17. if(be.getmessage ()! =null| | Constants.BLANK.equals (Be.getmessage (). Trim ())) {
  18. //Get error messages
  19. errormsg = Be.getmessage (). Trim ();
  20.                 }  
  21. } Else if(e instanceof runtimeexception) {
  22. //Unknown run-time exception
  23. runtimeexception re = (runtimeexception) e;
  24. Re.printstacktrace ();
  25. } Else{
  26. //Unknown critical exception
  27. E.printstacktrace ();
  28.             }  
  29. //Custom error messages
  30. httpservletrequest request = (httpservletrequest) actioninvocation
  31. . Getinvocationcontext (). get (Strutsstatics.http_request);
  32.               
  33.             /** 
  34. * Send error message to page
  35.              */  
  36. Request.setattribute ("errormsg", errormsg);
  37.           
  38.             /** 
  39. * log4j log
  40.              */  
  41. log log = Logfactory
  42. . GetLog (Actioninvocation.getaction (). GetClass ());
  43. if (e.getcause () = null) {
  44. Log.error (ErrorMsg, E);
  45. }Else{
  46. Log.error (ErrorMsg, E);
  47.             }  
  48.   
  49. return "error";
  50. }//... end of catch
  51.     }  

It is important to note that when you use instanceof to determine the type of exception, you must look from the child to the parent, such as Baseexception inheritance and RuntimeException, You must first determine whether it is baseexception to determine whether it is runtimeexception.

Finally, the error JSP page is displayed with a specific message:

Java code
    1. <body>
    2. <s:if test="%{#request. Errormsg==null}">
    3. <p> Sorry, the system has an unknown error </p>
    4. </s:if>
    5. <s:else>
    6. <p>${requestScope.errorMsg}</p>
    7. </s:else>
    8. </body>

The above method can intercept all the exceptions in the background code, but if a database connection exception cannot be caught, you can use STRUTS2 's global exception handling mechanism to handle it:

Java code
    1. <global-results>
    2. <result name="error" >/Web/common/page/error.jsp</result>
    3. </global-results>
    4.            
    5. <global-exception-mappings>
    6. <exception-mapping result="error" exception="java.lang.Exception" ></exception-mapping>
    7. </global-exception-mappings>

Above this is a very simple exception interceptor, you can use the custom exception, that will be more flexible.

The above exception interceptors can be replaced with many other technologies: such as spring aop,servlet filter, etc., according to the actual situation of the project.

"Supplemental" Ajax can also be intercepted, but because Ajax is an asynchronous operation, the action through the form of response directly return the data to the AJAX callback function, if an exception occurs, Ajax will not perform a page jump, so you must return the error message to the callback function, My Ajax for JSON data is doing this:

Java code
  1. /** 
  2. * Read the file to get the corresponding error message
  3.  */  
  4. httpservletresponse response = (httpservletresponse) actioninvocation.getinvocationcontext (). Get (  Strutsstatics.http_response);
  5. response.setcharacterencoding (Constants.encoding_utf8);
  6. /** 
  7. * Send error message to page
  8.  */  
  9. PrintWriter out;
  10. try {
  11. out = Response.getwriter ();
  12. message msg = new message (ERRORMSG);
  13. //Convert exception information to JSON format back to foreground
  14. Out.print (Jsonobject.fromobject (msg). toString ());
  15. } catch (IOException E1) {
  16. throw E;
  17. }  

Above is a personal humble opinion, do not shoot bricks, thank you.

Java Web Project Exception management

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.