SoFunction
Updated on 2025-05-09

Spring tutorial: Exception capture method

Overview

In Spring, the global exception catching method is encapsulated to facilitate us to handle and manage exceptions. Catching exceptions can solve the following business scenarios:

  1. Friendly return to the user prompt.
  2. Logging logs to facilitate troubleshooting
  3. Convenient to manage exceptions, etc.

The following program simulates an exception in the Controller:

import ;
import ;

/**
  * Global exception capture test
  * @author terry
  * @version 1.0
  * @date 2022/1/6 14:29
  */
@RestController
@RequestMapping("/gloab")
public class GloabExceptionController {

    @RequestMapping("/test1")
    public String test1(){
        // Simulate exceptions        int i = 1/0;
        return "success";
    }
}

Print Out

{
    "timestamp": "2022-01-06T06:51:26.538+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "",
    "path": "/gloab/test1"
}

Problems occur:

After sending the exception, the subsequent code is no longer executed, and the returned parameters are not what we need.

@RestControllerAdvice annotation

@RestControllerAdvice and @ControllerAdvice are both globally captured exception configuration classes. @RestControllerAdvice is more suitable for returning JSON data. @ControllerAdvice returns JSON and needs to add an additional @ResponseBody.

@RestControllerAdvice
class GloabExceptionHandler {

    @ExceptionHandler(value = )
    public String exceptionHandler(Exception e){
        ("ERROR: " + ());
        return "error";
    }
}

Print Out

error

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.