How to implement centralized exception handling in SpringBoot?
In Spring Boot, you can use the @ControllerAdvice annotation to implement centralized exception handling. Here is an example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse("500", ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(MyCustomException.class)
public ResponseEntity<ErrorResponse> handleCustomException(MyCustomException ex) {
ErrorResponse errorResponse = new ErrorResponse("400", ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@Data
@AllArgsConstructor
public static class ErrorResponse {
private String code;
private String message;
}
}
In the example above, we have defined a GlobalExceptionHandler class and used the @ControllerAdvice annotation to indicate that it is a global exception handling class. We then defined two exception handling methods to handle exceptions of type Exception and MyCustomException. In these methods, we can customize the error message and HTTP status code to be returned.
Note: To allow Spring Boot to scan the GlobalExceptionHandler class, make sure it is located in the application’s package or its subpackages.