How to handle global exceptions in Spring Boot?
Spring Boot offers a global exception handling mechanism, which allows you to create a global exception handling class to handle exceptions that occur in the system uniformly.
- Exception handler on a global scale
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleException(Exception ex) {
// 处理异常
// 返回自定义的错误信息
return new ResponseEntity<>("发生了错误", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
- Add the @ControllerAdvice annotation to the GlobalExceptionHandler class to indicate that this is a global exception handling class.
- Write an exception handling method in the GlobalExceptionHandler class, using the @ExceptionHandler annotation to specify the type of exception to handle. Handle the exception within the method and return a custom error message.
- Specific requirements can be met by handling different types of exceptions in the exception handling method, such as returning different error codes or error messages.
- When an exception occurs in the system, Spring Boot will automatically invoke the exception handling method in the GlobalExceptionHandler class and return custom error messages.
Please note that the global exception handling class needs to be scanned and can be placed in the same level or a subpackage of the main application class.
In this way, when an exception occurs in the system, the exception handling method in the global exception handling class will be automatically called, achieving unified logic for handling exceptions.