SoFunction
Updated on 2025-03-08

Detailed explanation of the @ControllerAdvice of SpringBoot handles global exceptions

@ControllerAdvice handles global exceptions

need

Today when building RestFul, we generally define the format of returning data such as:

{<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E--> 
​​​​​​​ "code": 0,
  "data": {},
  "msg": "The operation is successful"
}

But sometimes some bugs often occur. At this time, the consistency of the returned data is destroyed, resulting in the caller being unable to parse.

So we often define a global exception interceptor.

Note: ControllerAdvice annotation only intercepts the Controller and does not intercept the Interceptor exceptions.

introduce

In spring 3.2, the @ControllerAdvice annotation was added to intercept the global Controller exception. Note: the ControllerAdvice annotation only intercepts the Controller and will not intercept the Interceptor exception.

Code

package ;
import ;
import org.;
import org.;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
  * Exception interceptor processor
  *
  * @author chenmc
  */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";
    private static Logger log = ();
    //Exception during runtime    @ExceptionHandler()
    public String runtimeExceptionHandler(RuntimeException ex) {
        return resultFormat(1, ex);
    }
    //Null pointer exception    @ExceptionHandler()
    public String nullPointerExceptionHandler(NullPointerException ex) {
        return resultFormat(2, ex);
    }
    //Exception of type conversion    @ExceptionHandler()
    public String classCastExceptionHandler(ClassCastException ex) {
        return resultFormat(3, ex);
    }
    //IO exception    @ExceptionHandler()
    public String iOExceptionHandler(IOException ex) {
        return resultFormat(4, ex);
    }
    //Unknown method exception    @ExceptionHandler()
    public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {
        return resultFormat(5, ex);
    }
    //Array out of bounds exception    @ExceptionHandler()
    public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
        return resultFormat(6, ex);
    }
    //400 Error    @ExceptionHandler({})
    public String requestNotReadable(HttpMessageNotReadableException ex) {
        ("400..requestNotReadable");
        return resultFormat(7, ex);
    }
    //400 Error    @ExceptionHandler({})
    public String requestTypeMismatch(TypeMismatchException ex) {
        ("400..TypeMismatchException");
        return resultFormat(8, ex);
    }
    //400 Error    @ExceptionHandler({})
    public String requestMissingServletRequest(MissingServletRequestParameterException ex) {
        ("400..MissingServletRequest");
        return resultFormat(9, ex);
    }
    //405 Error    @ExceptionHandler({})
    public String request405(HttpRequestMethodNotSupportedException ex) {
        return resultFormat(10, ex);
    }
    //406 Error    @ExceptionHandler({})
    public String request406(HttpMediaTypeNotAcceptableException ex) {
        ("406...");
        return resultFormat(11, ex);
    }
    //500 Error    @ExceptionHandler({, })
    public String server500(RuntimeException ex) {
        ("500...");
        return resultFormat(12, ex);
    }
    //Stack overflow    @ExceptionHandler({})
    public String request*(*Error ex) {
        return resultFormat(13, ex);
    }
    //Other errors    @ExceptionHandler({})
    public String exception(Exception ex) {
        return resultFormat(14, ex);
    }
    private <T extends Throwable> String resultFormat(Integer code, T ex) {
        ();
        ((logExceptionFormat, code, ()));
        return (code, ());
    }
}  
package ;
import ;
import ;
import ;
import ;
import ;
/**
 * @author chenmc
 * @date 2017/10/12 17:18
 */
@Data
public class JsonResult implements Serializable{
    private int code;   //Return code is either 0, fails    private String msg; //Message prompt    private Map<String, Object> data; //Returned data    public JsonResult(){};
    public JsonResult(int code, String msg, Map<String, Object> data) {
         = code;
         = msg;
         = data;
    }
    public static String success() {
        return success(new HashMap<>(0));
    }
    public static String success(Map<String, Object> data) {
        return (new JsonResult(0, "Successful analysis", data));
    }
    public static String failed() {
        return failed("Resolution failed");
    }
    public static String failed(String msg) {
        return failed(-1, msg);
    }
    public static String failed(int code, String msg) {
        return (new JsonResult(code, msg, new HashMap<>(0)));
    }
}

This is enough for Spring Boot. If Spring Boot is not used, you need to add the following configuration to the SpringMvc configuration file.

<!-- Handle exceptions -->
    <context:component-scan base-package="" use-default-filters="false">  
	    <!-- base-package If multiple,use“,”Separation -->  
	    <context:include-filter type="annotation" expression="" />  
	    <!--Controller enhancement,Make oneContollerBecome a global exception handling class,类中use@ExceptionHandlerMethod annotation methods can handle allControllerAn exception that occurred-->  
	    <context:include-filter type="annotation" expression="" />  
	</context:component-scan>

This is the end of this article about the detailed explanation of @ControllerAdvice for handling global exceptions in SpringBoot. For more related content on @ControllerAdvice for handling global exceptions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!