thachlp / second-brain

Notes, codes for what I learned
MIT License
1 stars 0 forks source link

@RestControllerAdvice #16

Closed thachlp closed 1 year ago

thachlp commented 1 year ago

@RestControllerAdvice is a specialization of @ControllerAdvice annotation which is implemented to handle the exceptions thrown by the @RestController. It allows us to handle exceptions across the whole application in a global, consistent manner.

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}