Sunday, September 15, 2024

How to handle exceptions in Spring boot?

 1. Controller Advice with @ExceptionHandler

Using @ControllerAdvice in combination with @ExceptionHandler allows you to handle exceptions globally across your application or for specific controllers.

 

@ControllerAdvice

public class GlobalExceptionHandler {

 

    @ExceptionHandler(ResourceNotFoundException.class)

    @ResponseStatus(HttpStatus.NOT_FOUND)

    public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) {

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

    }

 

    @ExceptionHandler(Exception.class)

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)

    public ResponseEntity<String> handleGeneralException(Exception ex) {

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

    }

}

 @ControllerAdvice: Designates the class as a global exception handler.

@ExceptionHandler: Specifies the type of exception to handle.

@ResponseStatus: Sets the HTTP status code.

No comments:

Post a Comment