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);

    }

}

Top Blogs
How do you handle exceptions in a Spring Boot application? Published at:- How do you schedule tasks in a Spring Boot application? Published at:- Can you explain how you would use Spring Boot to build a RESTful API for a project? Published at:- what is new in Spring Boot Published at:- What is new in different version of SPring boot Security Published at:-
R4R.co.in Team
The content on R4R is created by expert teams.