SpringBoot2 Global Exception Handling

Source: Internet
Author: User
Tags log log throwable

Refer to the following types of anomalies in this article:

Global exception handling is a more important feature that is commonly used in projects.
A request can be divided into three stages to perform a global exception handling.
One: Before entering the controller, such as requesting a nonexistent address, 404 error.
Two: In the execution of @requestmapping, before entering the logic processing stage. For example, the wrong type of argument is passed.
Three: When the above is normal, the logic code in the controller execution of the exception. such as NullPointerException.

Put the written global exception-handling class directly into the project, and configure @controller to load the class into spring for use without any configuration.

Here are the exception handling classes I wrote:

Package Com.archibladwitwicke.springboot2.chapter03.controller;import Com.fasterxml.jackson.databind.objectmapper;import Org.apache.commons.logging.log;import Org.apache.commons.logging.logfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.boot.autoconfigure.web.servlet.error.abstracterrorcontroller;import Org.springframework.boot.web.servlet.error.defaulterrorattributes;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.servlet.modelandview;import Javax.servlet.servletexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import java.io.IOException; Import Java.util.collections;import java.util.hashmap;import Java.util.Map; @Controllerpublic class    Globalerrorcontroller extends Abstracterrorcontroller {private static final String Error_path = "/error"; Private log log = Logfactory.getlog (GlobalerrorcoNtroller.class);    @Autowired Objectmapper Objectmapper;    Public Globalerrorcontroller () {Super (New defaulterrorattributes ()); } @RequestMapping (Error_path) public Modelandview Geterrorpath (httpservletrequest request, HttpServletResponse Respo NSE) {map<string, object> model = Collections.unmodifiablemap (geterrorattributes (Request, FA        LSE));        Throwable cause = getcause (request);        int status = (Integer) model.get ("status");        Error message String message = (string) model.get ("message");        Friendly hint String errormessage = geterrormessage (cause);        String Requestpath = (string) model.get ("path");        Background print log information to facilitate error log.info (status + ":" + message, cause);        Log.info ("Requestpath---" + ":" + Requestpath);        Background print log information to facilitate error log.info (message, cause);        Response.setstatus (status); if (!isjsonrequest (request, model)) {Modelandview view = new Modelandview ("/error.BTL ");            View.addallobjects (model);            View.addobject ("status", status);            View.addobject ("ErrorMessage", errormessage);            View.addobject ("cause", cause);        return view;            } else {map<string, object> error = new hashmap<> ();            Error.put ("Success", false);            Error.put ("ErrorMessage", GetErrorMessage (cause));            Error.put ("message", message);            Writejson (response, error);        return null; }} Private Boolean isjsonrequest (HttpServletRequest request, map<string, object> model) {//fix bugs in this class        , you cannot get requestpath String Requestpath = (string) model.get ("path") using request.        if (Requestpath.endswith (". JSON")) {return true; } else {return (Request.getheader ("accept"). Contains ("Application/json") | | (Request.getheader ("X-requested-with")! = null && request.getheader ("X-requested-with"). ContaIns ("XMLHttpRequest"))); }} private void Writejson (httpservletresponse response, map<?,? > Error) {response.setcontenttype ("AP        Plication/json;charset=utf-8 ");        try {response.getwriter (). Write (objectmapper.writevalueasstring (error));        } catch (IOException e) {e.printstacktrace ();    }} private String GetErrorMessage (Throwable ex) {/* Do not show verbose error to front end */return "Server error, please contact Administrator"; } private Throwable Getcause (HttpServletRequest request) {Throwable error = (throwable) request.getattribute ("J        Avax.servlet.error.exception ");                if (Error! = null) {while (Error instanceof servletexception && error.getcause ()! = null) {            Error = ((servletexception) error). Getcause ();    }} return error;    } @Override Public String Geterrorpath () {return error_path; }}


This method can be modified according to the project, which will judge the type of Ajax request, and the remainder can not be modified:

Private Boolean isjsonrequest (HttpServletRequest request, map<string, object> model) {        //fix bugs, in this class, Cannot get Requestpath        String Requestpath = (string) model.get ("path") using request.        if (Requestpath.endswith (". JSON")) {            return true;        } else {            return (Request.getheader ("accept"). Contains ( "Application/json") | | (Request.getheader ("X-requested-with")! = null                    && request.getheader ("X-requested-with"). Contains (" XMLHttpRequest ")));        }    }


This exception class can intercept the above three exception cases, displaying custom exception handling pages or exception handling data.

SpringBoot2 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.