How do you handle exceptions in a Spring Boot application?

Categories: Spring Boot

To handle exceptions in a Spring Boot application, you can use the @ControllerAdvice and @ExceptionHandler annotations. Create a class annotated with @ControllerAdvice to handle exceptions globally.

@ControllerAdvice

public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)

    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {

        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);

    }

    @ExceptionHandler(Exception.class)

    public ResponseEntity<String> handleException(Exception ex) {

        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);

    }

}

R4R.co.in Team
The content on R4R is created by expert teams.