SPRINGMVC Implementing Global Exception handling

Source: Internet
Author: User

    • Configuring global exception Handling in SPRINGMVC
class= "Cn.znx.blog.exception.MyExceptionResolver" ></bean>
    • Defining global Exception Handling classes: Handlerexceptionresolver interface required
 Packagecn.znx.blog.exception;ImportCom.google.gson.Gson;ImportOrg.springframework.web.bind.annotation.ResponseBody;ImportOrg.springframework.web.method.HandlerMethod;ImportOrg.springframework.web.servlet.HandlerExceptionResolver;ImportOrg.springframework.web.servlet.ModelAndView;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJava.util.HashMap;ImportJava.util.Map; Public classMyexceptionresolverImplementsHandlerexceptionresolver { PublicModelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler, Exception Exception) {//Print error messageException.printstacktrace (); //Defining error MessagesString message = "The system is busy, please try again later!" "; if(Exceptioninstanceofmyexception) {Message=((myexception) exception). GetMessage (); }        //Determine request typeHandlermethod Handlermethod =(Handlermethod) handler; Responsebody Responsebody= Handlermethod.getmethod (). Getannotation (Responsebody.class); //if it is a JSON request, the JSON data is returned        if(responsebody!=NULL) {Map<String,Object> Responsemap =NewHashmap<string,object>(); Responsemap.put ("Code", "999999"); Responsemap.put ("Message", message); String JSON=NewGson (). ToJson (Responsemap); Response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Application/json;charset=utf-8"); Try{response.getwriter (). write (JSON);            Response.getwriter (). Flush (); } Catch(Exception e) {e.printstacktrace (); }            return NewModelandview (); }        //If the request is a jump page//Page ForwardingModelandview Modelandview =NewModelandview (); //upload error message to pageModelandview.addobject ("Message", message); //point to Error pageModelandview.setviewname ("Error"); returnModelandview; }}
    • Custom exceptions
Package Cn.znx.blog.exception;import Com.google.gson.gson;import Org.springframework.web.bind.annotation.responsebody;import Org.springframework.web.method.handlermethod;import Org.springframework.web.servlet.handlerexceptionresolver;import Org.springframework.web.servlet.ModelAndView; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Java.util.hashmap;import Java.util.map;public class Myexceptionresolver implements Handlerexceptionresolver {public M                                         Odelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler,        Exception Exception) {//Print error message exception.printstacktrace (); Define error message String message = "The system is busy, please try again later!"        ";        If (Exception instanceof myexception) {message = ((myexception) exception). GetMessage ();        }//Judgment request type Handlermethod Handlermethod = (handlermethod) handler; Responsebody ResponseboDY = Handlermethod.getmethod (). Getannotation (Responsebody.class); If it is a JSON request, the JSON data is returned if (responsebody!=null) {map<string,object> Responsemap = new Hashmap<stri            Ng,object> ();            Responsemap.put ("Code", "999999");            Responsemap.put ("message", message);            String json = new Gson (). ToJson (Responsemap);            Response.setcharacterencoding ("UTF-8");            Response.setcontenttype ("Application/json;charset=utf-8");                try {response.getwriter (). write (JSON);            Response.getwriter (). Flush ();            } catch (Exception e) {e.printstacktrace ();        } return new Modelandview ();        }//If it is a jump page request//page forward Modelandview Modelandview = new Modelandview ();        Upload error message to page modelandview.addobject ("message", message);        Point to Error page Modelandview.setviewname ("error");    return modelandview; }}
    • To define a JSON response class:
@Datapublic class Result {    //status code    private String code;    Error message    private String message;    or JSON    private hashmap<string,object> data = new hashmap<> ();    Logon failure public    static result error (String string) {        result result = new result ();        Result.setcode ("999999");        if (Stringutils.isempty (String)) {            result.setmessage ("Login Failed");        } else{            result.setmessage (string);        }        return result;    }    Add data public    Result Add (String key,object value) {        this.getdata (). put (key,value);        return this;    }    Login succeeded public    static result success () {        result result = new result ();        Result.setcode ("000000");        Result.setmessage ("Login Successful");        return result;    }    }

SPRINGMVC Implementing 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.