SpringBoot 2 Fast Integration | Unified exception handling

Keywords: Java JSON

Introduction to annotations related to unified exception handling


Declarations are used on classes to specify that class is a control enhancer class. If you want to declare that the returned results are RESTFull-style data, you need to add @ResponseBody to the method that declares the @ExceptionHandler annotation.


Declarations are used on classes to specify that class is a control enhancer class. And declare that the returned results are RESTFull-style data, without adding the method to declare the @ExceptionHandler annotation


Declarations are used in methods to specify exceptions that need to be intercepted uniformly. For example: @ExceptionHandler(value = Exception.class)

Actual Operation

Define message classes:

Define a message class that RESTFull returns JSON data, which contains member variables as follows:

  • Code: Error code, 0 means no exception information.
  • message: Exception prompt information.
  • date: No exception is to return specific information.
public class ReturnMessage<T> {
    private Integer code;//Error code
    private String message;//Tips
    private T date;//Return specific content
    public ReturnMessage(Integer code, String message, T date) {
        this.code = code;
        this.message = message;
        this.date = date;
    //Omit get and set method

** Message class processing tool class: **

Mainly used to deal with successful or failed message processing, the toolkit mainly includes three methods:

  1. Successful processing of data containing entities
  2. Successful processing of no entity data
  3. Failure handling

The code is as follows:

public class ReturnMessageUtil {
     * No exception request succeeded and specific content returned
     * @param object
     * @return
    public static ReturnMessage<Object> sucess(Object object) {
        ReturnMessage<Object> message = new ReturnMessage<Object>(0,"sucess",object);
        return message;
     * Successful no exception request and no specific return
     * @return
    public static ReturnMessage<Object> sucess() {
        ReturnMessage<Object> message = new ReturnMessage<Object>(0,"sucess",null);
        return message;
     * Have custom error exception information
     * @param code
     * @param msg
     * @return
    public static ReturnMessage<Object> error(Integer code,String msg) {
        ReturnMessage<Object> message = new ReturnMessage<Object>(code,msg,null);
        return message;

Custom exception classes:

We use custom system exception classes to perform checking-related operations. Custom system exception classes inherit RuntimeException and declare member variables named code to represent different types of exceptions.

It is mainly used to get custom exception code after exception interception, and set the code to the message class.

public class SbException extends RuntimeException{

    private Integer code;
    public Integer getCode() {
        return code;
    public void setCode(Integer code) {
        this.code = code;
    public SbException(Integer code,String message) {
        this.code = code;

Define uniform exception interception classes:

By declaring @RestController Advice, this class is a RESTFul-style exception handling control enhancer class, declaring @ExceptionHandler in the handle method, and specifying the exception class to intercept in the annotation. The code is as follows:

public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    @ExceptionHandler(value = Exception.class)
    public ReturnMessage<Object> handle(Exception exception) {
        if(exception instanceof SbException) {
            SbException sbexception = (SbException)exception;
            return ReturnMessageUtil.error(sbexception.getCode(), sbexception.getMessage());
        }else {
            logger.error("Systematic anomaly {}",exception);
            return ReturnMessageUtil.error(-1, "Unknown anomaly"+exception.getMessage());


Custom exception and system exception are tested respectively. Custom exception is tested by / error / custom and unknown system exception is tested by / error/unknown. The code is as follows:

public class DemoException {
    @GetMapping(value = "custome")
    public void customException() {
        SbException sbe = new SbException(100, "This is a custom exception!");
        throw sbe;
    @GetMapping(value = "unknown")
    public void unknownException() {
        int i = 0;
        int b = 1/i;

Test results:

Posted by xentia on Wed, 04 Sep 2019 01:43:56 -0700