Return JSON exception data after Spring MVC global exception

Source: Internet
Author: User
Tags getmessage throw exception throwable

Spring MVC Global Exception Returns JSON exception data problem:

The current project is a background support for mobile apps, developed using spring MVC + mybaits + Shiro. The backend service interacts with the phone to send JSON data. If an exception occurs in the background, it will directly return to the exception page, showing the exception, if the 404 request is not a resource or 500 of such a problem, may result in the return of 404 and 500 exception page, mobile phone processing is very troublesome, in order to solve this problem, you need to do the global exception handling.

Solution: (1) Customize or use the various exception handlers that spring comes with

For example, spring annotation-based exception resolver Annotationhandlermethodexceptionresolver, Spring comes with a global exception handler Simplemappingexceptionresolver, the custom Implementation of Spring's global exception resolver handlerexceptionresolver to handle.

Annotationhandlermethodexceptionresolver What I now know is that I need to define the type of the exception on the method, and if the exception type is too much, it's too cumbersome to write the code, so I think it's bad. (The warrior knows not to define the type of exception to handle all exceptions, you can leave a message to tell me, thank you!) )

spring comes with global exception processor Simplemappingexceptionresolver is also more cumbersome, need to configure too many places, do not like to use.

Custom implementation of Spring's global exception resolver handlerexceptionresolver to handle what I think is most convenient, of course, this is for my current business scenario, It's not absolute.

Due to the Java exception mechanism, if a large number of exceptions, the performance of the JVM will have a great impact, the performance is reduced by 10%, the weight of the JVM memory overflow, I personally think it is best not to throw the exception, so I mainly use the Custom implement spring's global exception resolver handlerexceptionresolver to handle business problems.


(2)custom implementation of Spring's global exception resolver handlerexceptionresolver

2.1 Only need to define a global exception handling class in the SPRING-MVC configuration file

        <!--global exception handling--        <bean id= "Exceptionhandler" class= "Com.aaa.bbb.exception.DefaultExceptionHandler"/ >
2.2 ImplementationHandlerexceptionresolver(The first method of implementation)

This way need to download Fastjson, I use 1.2.6 version, can be Baidu after the download.

public class Defaultexceptionhandler implements Handlerexceptionresolver {  private static Logger log = Loggerfactory . GetLogger (Defaultexceptionhandler.class);    Public Modelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler,  Exception ex) {          Modelandview mv = new Modelandview ();        /* Return with Fastjsonjsonview view provided by Fastjson, no catch exception required *        /Fastjsonjsonview view = new Fastjsonjsonview ();        map<string, object> attributes = new hashmap<string, object> ();        Attributes.put ("Code", "1000001");        Attributes.put ("msg", Ex.getmessage ());        View.setattributesmap (attributes);        Mv.setview (view);         Log.debug ("Exception:" + Ex.getmessage (), ex);        return MV;    
2.2 ImplementationHandlerexceptionresolver(The second way of implementation)

public class Defaultexceptionhandler implements Handlerexceptionresolver {  private static Logger log = Loggerfactory . GetLogger (Defaultexceptionhandler.class);    Public Modelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler,  Exception ex) {          Modelandview mv = new Modelandview ();                /* Use response to return */        Response.setstatus (HttpStatus.OK.value ());//Set Status code        Response.setcontenttype ( Mediatype.application_json_value); Set contenttype        response.setcharacterencoding ("UTF-8");//Avoid garbled        response.setheader ("Cache-control", " No-cache, Must-revalidate ");        try {            response.getwriter (). Write ("{\" success\ ": False,\" msg\ ": \" "+ ex.getmessage () +" \ "}");        } catch ( IOException e) {           log.error ("Communication with client exception:" + E.getmessage (), E);        }        Log.debug ("Exception:" + Ex.getmessage (), ex);        return mv;    }}

In this case, the Spring MVC Global exception handling returns JSON, and after an exception, the JSON data is returned, and no more annoying exception content. However, this is not complete, you need to add exception code 404 or 500 processing in Web. XML to finish.

(1) Web page exception handling configuration

1.1 <exception-type>java.lang.Throwable</exception-type> represents an exception that occurs java.lang.Throwable type, <location >/error_500</location> represents to/error_500 address processing,

For example, the user requests "Http://www.a.com/user/login/getUser", the app name is user, and if the request occurs java.lang.Throwable, the request goes to "http://www.a.com/user/error_500"

1.2 <error-code>404</error-code> indicates that a 404 request has failed,<location>/error_404</location> represents to/error_ 404 Processing,

For example, the user requests "Http://www.a.com/user/login/getUser", the application name is user, if the user requests a 404 exception, the request resources can not be found, then the request will go to "http://www.a.com/user/error_404"

<!--Web Exception page processing--><error-page><exception-type>java.lang.throwable</exception-type>< Location>/error_500</location></error-page><error-page><exception-type> java.lang.exception</exception-type><location>/error_404</location></error-page>< error-page><error-code>500</error-code><location>/error_500</location></ error-page><error-page><error-code>501</error-code><location>/error_500</ location></error-page><error-page><error-code>502</error-code><location>/ error_500</location></error-page><error-page><error-code>404</error-code>< location>/error_404</location></error-page><error-page><error-code>403</ Error-code><location>/error_404</location></error-page><error-page><error-code >400</error-code><location>/error_404</location></error-page> 

(2) Background processing

If the above exception occurs, the request will go to "http://www.a.com/user/error_404", then in the background need to do the appropriate processing, is the controller layer to define the way to handle the exception

/** * Request Exception * @return * @throws Exception * String * * @RequestMapping (value = "/error_404", produces = "text/html;charset=ut F-8 ") @ResponseBodypublic String error_404 () throws Exception {  return" {\ "msg\": \ "page not found \" \ "code\": \ "1000001\"} " ;} /** * Server Exception * @return * String * * @RequestMapping (value = "/error_500", produces = "text/html;charset=utf-8") public String E Rror_500 () {<pre name= "code" class= "Java" >                return "{\" msg\ ": \" Server processing failed \ "\" code\ ": \" 1000002\ "}";}


Finally, basically all of the anomalies can be captured, can be abnormal, the user-friendly prompt, but also to avoid server-side throw exception caused by the problem.




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Return JSON exception data after Spring MVC global exception

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.