Use spring MVC handlerexceptionresolver to handle exceptions for 400 errors

Source: Internet
Author: User

Last night an action set a large object, but submitted has been submitted not past, the background also did not have any error, and finally the online search, using handlerexception to catch this error, the specific article is as follows:

Pring MVC is really powerful and leaves a hook in every place you think and imagine, to insert a custom implementation, transparently replace the default implementation,
Interceptor stack structure design is very powerful, a variety of attempts to parse, URL mapping a variety of implementations, Locale Resolver, Theme resolver
, multipart file Resolver,excepiton Hanlder resolver, and so on, allows spring MVC to undergo dramatic changes from 1.0 to 3.0,
Can still be backwards compatible, and supports the cool restful style and the powerful annotations for simplifying XML configuration.
These features are often used in our projects, but Excepiton Hanlder resolver may be an uncommon thing, because we usually
The processing is usually not very complex, in many cases, just according to the exception or HTTP error code to jump to the error page, this is Jsp/servlet can
To be done, in the Web.xml configuration can be.

I met a thing today, let me want to use handlerexceptionresolver this dongdong to handle the exception. Ready to put the self-service system into line today,
So the log level from debug to info, resulting in no catch of the runtime exception in log records, and then tracked the original spring to handle the exception of the log,
Use debug directly, not error, so log level set to info causes exception to be logged, and look at spring's source code:

Check registerer handlerexceptionresolvers  
... Modelandview EXMV = null;  
for (Iterator it = This.handlerExceptionResolvers.iterator (); EXMV = = null && it.hasnext ();) {  
Handlerexceptionresolver resolver = (handlerexceptionresolver) it.next ();  
EXMV = resolver.resolveexception (Request, response, Handler, ex);  
}  
if (EXMV!= null) {  
if (logger.isdebugenabled ()) {  
logger.debug ("Handler execution resulted in Exception-forward ing to resolved error view: "+ EXMV, ex);  
}  
Webutils.exposeerrorrequestattributes (Request, EX, Getservletname ());  
return EXMV;  

You can see that you can insert your own handlerexceptionresover to fix this problem, and we can handle the exception and log at any resolveexception method. can also
Personalize the error message and upload it to the view layer display.
We only have simple requirements, that is, the exception of the catch is recorded in log, the complete information of the exception in a hidden area of the error page, easy to find the cause of the error.
First we realize Handlerexceptionresolver

Package com.qunar.advertisement.exception;  
Import Java.util.HashMap;  

Import Java.util.Map;  
Import Javax.servlet.http.HttpServletRequest;  

Import Javax.servlet.http.HttpServletResponse;  
Import Org.apache.log4j.Logger;  
Import Org.springframework.web.servlet.HandlerExceptionResolver;  

Import Org.springframework.web.servlet.ModelAndView;  

Import Com.qunar.advertisement.utils.StringPrintWriter; public class Qadhandlerexceptionresolver implements handlerexceptionresolver{private static Logger Logger = Logger.  
    GetLogger (Qadhandlerexceptionresolver.class); @Override public Modelandview resolveexception (httpservletrequest request, HttpServletResponse respons E, Object handler, Exception ex) {logger.error ("Catch Exception:", ex);//To log the exception information of the slip through the logs Map<string,o  
        bject> map = new hashmap<string,object> ();  
        Stringprintwriter strintprintwriter = new Stringprintwriter (); Ex.printstacktrace (StrintprintwritER);  
    Map.put ("ErrorMsg", strintprintwriter.getstring ());//Pass the error message to view return new Modelandview ("error", map);   }  

}

We also need an auxiliary class Stringprintwriter, because the Ex.printstacktrace parameter has only one printwriter type, the Java band StringWriter
Not available, so we need to implement an adorner's stringprintwriter ourselves.

Package com.qunar.advertisement.utils;  

Import Java.io.PrintWriter;  
Import Java.io.StringWriter;  

public class Stringprintwriter extends printwriter{public  

    stringprintwriter () {  
        super (new StringWriter ());  
    } Public  

    stringprintwriter (int initialsize) {  
          super (new StringWriter (initialsize));  
    }  

    Public String getString () {  
          flush ();  
          Return ((StringWriter) this.out). toString ();  

    @Override public  
    String toString () {return  
        getString ();  
    }  
}  

All we need to do is configure it in the Spring.xml:

<bean class= "Com.qunar.advertisement.exception.QADHandlerExceptionResolver" >  
</bean>  

We display an error message in the error page hidden area:

<div style= "Display:none;" > <c:out value= "${errormsg}" ></c:out> </div> 

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.