SPRINGMVC using Handlerexceptionresolver for global exception handling

Source: Internet
Author: User
Tags getmessage throwable

Today we use the exception handling in the SPRINGMVC, which is recorded here and will be used later.

Spring MVC provides a handlerexceptionresolver interface that can be used for uniform exception handling.

The actual code of the project is as follows:

 Packageorg.jeecgframework.core.common.exception;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJava.io.StringWriter;ImportJava.util.HashMap;ImportJava.util.Map;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.log4j.Logger;ImportOrg.jeecgframework.core.common.model.json.AjaxJson;ImportOrg.jeecgframework.core.util.ExceptionUtil;ImportOrg.jeecgframework.core.util.JSONHelper;Importorg.jeecgframework.core.util.oConvertUtils;ImportOrg.jeecgframework.web.system.service.SystemService;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.stereotype.Component;ImportOrg.springframework.web.servlet.HandlerExceptionResolver;ImportOrg.springframework.web.servlet.ModelAndView;/*** Spring MVC Global Handling exception capture distinguishes between Ajax and ordinary requests based on requests, responding separately. * First, the exception information is output to the log. * Second, the first 50 characters to intercept the exception details are written to the T_s_log in the log table. */@Component Public classGlobalexceptionresolverImplementsHandlerexceptionresolver {@AutowiredPrivateSystemservice Systemservice; //Logging log Information    Private Static FinalLogger log =Logger. GetLogger (globalexceptionresolver.class); //Record database maximum character length    Private Static Final intWirte_db_max_length = 1500; //Record database maximum character length    Private Static Final  ShortLog_level = 6; //Record database maximum character length    Private Static Final  Shortlog_opt = 3; /*** Unified Processing of exception information, distinguish between asynchronous and synchronous requests, respectively processing*/     PublicModelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler, Ex Ception ex) {BooleanIsajax =Isajax (Request,response); Throwable deepestexception=Deepestexception (ex); returnprocessexception (Request, response, Handler, deepestexception, Isajax); }    /*** Determines whether the current request is an asynchronous request. */    Private BooleanIsajax (httpservletrequest request, httpservletresponse response) {returnOconvertutils.isnotempty (Request.getheader ("X-requested-with")); }    /*** Get the original source of the anomaly, the place where the exception was originally thrown*/    Privatethrowable deepestexception (Throwable e) {throwable tmp=e; intBreakpoint = 0;  while(Tmp.getcause ()! =NULL){            if(Tmp.equals (Tmp.getcause ())) { Break; } tmp=Tmp.getcause (); Breakpoint++; if(breakpoint>1000){                 Break; }        }         returntmp; }    /*** Handle Exceptions. * @paramRequest *@paramResponse *@paramHandler *@paramdeepestexception *@paramIsajax *@return     */    PrivateModelandview processexception (httpservletrequest request, httpservletresponse response, Object handler, Throwable EX,BooleanIsajax) {        //Step One, the exception information is logged in the log file.Log.error ("Global handling Exception Capture:", ex); //Step Two, the exception information records intercepted the first 50 characters written to the database.Logdb (ex); //step three, the ordinary request and AJAX requests are processed separately.        if(isajax) {returnProcessajax (REQUEST,RESPONSE,HANDLER,EX); }Else{            returnProcessnotajax (REQUEST,RESPONSE,HANDLER,EX); }    }    /*** Exception information record intercepts the first 50 characters written in the database *@paramex*/    Private voidLogdb (Throwable ex) {//String exceptionmessage = Getthrowablemessage (ex);String exceptionmessage = "Error exception:" +ex.getclass (). Getsimplename () + ", error description:" +Ex.getmessage (); if(Oconvertutils.isnotempty (exceptionmessage)) {if(Exceptionmessage.length () >wirte_db_max_length) {Exceptionmessage= exceptionmessage.substring (0, wirte_db_max_length);    }} systemservice.addlog (Exceptionmessage, Log_level, log_opt); }    /*** Ajax exception handling and return. * @paramRequest *@paramResponse *@paramHandler *@paramdeepestexception *@return     */    PrivateModelandview Processajax (httpservletrequest request, httpservletresponse response, Object handler, Throwable deepestexception) {Modelandview empty=NewModelandview (); //Response.setcontenttype ("Application/json");Response.setheader ("Cache-control", "No-store"); Ajaxjson JSON=NewAjaxjson (); Json.setsuccess (true);        Json.setmsg (Deepestexception.getmessage ()); PrintWriter PW=NULL; Try{PW=Response.getwriter ();            Pw.write (Jsonhelper.bean2json (JSON));        Pw.flush (); } Catch(IOException e) {e.printstacktrace (); }finally{pw.close ();        } empty.clear (); returnempty; }    /*** Normal page exception handling and return. * @paramRequest *@paramResponse *@paramHandler *@paramdeepestexception *@return     */    PrivateModelandview Processnotajax (httpservletrequest request, httpservletresponse response, Object handler, Thro Wable ex) {String exceptionmessage=Getthrowablemessage (ex); Map<string, object> model =NewHashmap<string, object>(); Model.put ("Exceptionmessage", Exceptionmessage); Model.put ("Ex", ex); return NewModelandview ("Common/error", model); }    /*** return error message String * *@paramex * Exception *@returnerror message string*/     PublicString Getthrowablemessage (Throwable ex) {StringWriter SW=NewStringWriter (); PrintWriter PW=NewPrintWriter (SW);        Ex.printstacktrace (PW); returnsw.tostring (); }}。 

Spring-mvc.xml configuration:

<!---    < id = "Exceptionhandler"         class = "Org.jeecgframework.core.common.exception.GlobalExceptionResolver" />

This article transferred from: http://blog.csdn.net/wuqiwei521/article/details/71191505

SPRINGMVC using Handlerexceptionresolver for global exception handling

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.