Three ways to handle spring global exceptions

Source: Internet
Author: User
Tags getmessage

In the development of the Java EE project, whether it is the operation process of the underlying database, the processing of the business layer, or the processing process of the control layer, it is unavoidable to encounter all kinds of unpredictable and unpredictable anomalies to deal with. Each process is handled separately, the System's code coupling is high, the workload is large and not uniform, the maintenance workload is also very large. so, can we decouple all types of exception handling from each processing process, so as to ensure that the function of the relevant processing process is relatively single, but also to achieve the unified processing and maintenance of abnormal information? The answer is Yes. The following describes the resolution and implementation process of using spring MVC to handle exceptions uniformly.

    • Using the simplemappingexceptionresolver provided by spring MVC
    • Implementing Spring's exception Handling interface Handlerexceptionresolver customizing its own exception handler
    • Using @exceptionhandler annotations for exception handling

(a) Simplemappingexceptionresolver
Using this method has the advantages of simple integration, good extensibility, no intrusion on existing code, but it can only get exception information, and if there is an exception, it does not apply to the need to obtain data other than the Exception.

1 @Configuration2 @EnableWebMvc3@ComponentScan (basepackages = {"com.balbala.mvc.web")})4  public classWebmvcconfigextendswebmvcconfigureradapter{5 @Bean6      publicsimplemappingexceptionresolver simplemappingexceptionresolver ()7     {8Simplemappingexceptionresolver B =NewSimplemappingexceptionresolver ();9Properties mappings =NewProperties ();TenMappings.put ("org.springframework.web.servlet.PageNotFound", "page-404"); oneMappings.put ("org.springframework.dao.DataAccessException", "data-access"); aMappings.put ("org.springframework.transaction.TransactionException", "transaction-failure"); - b.setexceptionmappings (mappings); -         returnb; the     } -}

(ii) Handlerexceptionresolver
Compared to the first, Handlerexceptionresolver can accurately display the defined exception handling page and achieve the goal of uniform exception handling.
1. Defining a class implementation Handlerexceptionresolver interface

1  public classGlobalhandlerexceptionresolverImplementsHandlerexceptionresolver {2  Private Static FinalLogger LOG = Loggerfactory.getlogger (globalhandlerexceptionresolver.class); 3    /**     4 * Handle all the abnormal information here.5     */    6 @Override7     publicmodelandview resolveexception (httpservletrequest req, httpservletresponse Res p, Object o, Exception Ex) {8 Ex.printstacktrace (); 9        if(exinstanceofAthenaexception) {    Ten            //athenaexception for a custom exception one Ex.printstacktrace ();  a printwrite (ex.tostring (), resp);  -            return NewModelandview ();  -         }     the        //rspmsg for a custom handling exception information class -        //Responsecode interface for a custom error code -Rspmsg unknownexception =NULL;  -        if(exinstanceofNullpointerexception) {         +Unknownexception =NewRspmsg (responsecode.code_unknown, "business Empty exception",NULL); -}Else {           +Unknownexception =NewRspmsg (responsecode.code_unknown, ex.getmessage (),NULL); }       a printwrite (unknownexception.tostring (), resp);  at            return NewModelandview ();  -    }   -  -    /**      - * Add error information to response -    *      in    * @parammsg -    * @paramResponse to    * @throwsIOException +    */    -      public Static voidprintwrite (String msg, httpservletresponse Response) { the          Try {            *PrintWriter PW =Response.getwriter ();  $ Pw.write (msg); Panax Notoginseng Pw.flush ();  - Pw.close ();  the}Catch(Exception E) { + E.printstacktrace ();  a           }    the     } +}

The exception handling implemented in this way can be translated for different exceptions and their own defined exception codes, then output to response and displayed on the front end.

(c) @ExceptionHandler

1. First define a parent class to implement some basic methods

1  public classBaseglobalexceptionhandler {2      protected Static FinalLogger Logger =NULL; 3      protected Static FinalString Default_error_message = "the system is busy, please try again later"; 4 5      protectedModelandview handleError (httpservletrequest req, httpservletresponse rsp, Exception e, String viewName, httpstatus StatusthrowsException {6          if(annotationutils.findannotation (e.getclass (), Responsestatus.class) !=NULL)       7          Throwe; 8String errormsg = Einstanceofmessageexception?e.getmessage (): default_error_message; 9String Errorstack =throwables.getstacktraceasstring (e); Ten  oneGetLogger (). error ("Request: {} raised {}", Req.getrequesturi (), errorstack);  a          if(ajax.isajax (req)) { -               returnhandleajaxerror (rsp, errormsg, status);  -          }         the          returnhandleviewerror (req.getrequesturl (). toString (), errorstack, errormsg, viewName);  -      }    -  -      protectedmodelandview handleviewerror (string url, string errorstack, string errormessage, string ViewName) { +Modelandview Mav =NewModelandview ();  -Mav.addobject ("exception", errorstack);  +Mav.addobject ("url", url);  aMav.addobject ("message", errormessage);  atMav.addobject ("timestamp",NewDate ());  - Mav.setviewname (viewName);  -           returnmav;  -        }     -  -      protectedModelandview handleajaxerror (httpservletresponse rsp, String errormessage, httpstatus Status)throwsIOException { inRsp.setcharacterencoding ("UTF-8");  - rsp.setstatus (status.value ());  toPrintWriter writer =Rsp.getwriter (); + Writer.write (errormessage);  - Writer.flush ();  the             return NULL;  *       }     $ Panax Notoginseng       publicLogger getLogger () { -            returnLoggerfactory.getlogger (baseglobalexceptionhandler.class); the      }  +}

2. How to handle the exception implementation that you need to capture

1 @ControllerAdvice2  public classGlobalexceptionhandlerextendsBaseglobalexceptionhandler {3 4       //for example, a 404 anomaly would be captured by this method.5@ExceptionHandler (nohandlerfoundexception.class)    6 @ResponseStatus (httpstatus.not_found)7         publicModelandview handle404error (httpservletrequest req, httpservletresponse rsp, Exception e)throwsException {8              returnHandleError (req, rsp, e, "error-front", httpstatus.not_found); 9        }    Ten  one       //500 of exceptions will be captured by this method a@ExceptionHandler (Exception.class)       - @ResponseStatus (httpstatus.internal_server_error) -        publicModelandview handleError (httpservletrequest req, httpservletresponse rsp, Exception e)throwsException { the              returnHandleError (req, rsp, e, "error-front", httpstatus.internal_server_error);  -       }     -  -      //TODO You can also write a method to capture your custom exception +      //TRY now!!! -  + @Override a        publicLogger getLogger () { at             returnLoggerfactory.getlogger (globalexceptionhandler.class);  -       } -  -}

Three ways to handle spring global exceptions

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.