Global Exception Handling With ControllerAdvice in Spring Boot

Posted By : Avnish Yadav | 24-Sep-2019

Spring provides @ControllerAdvice annotation which allows us to write some global code which can be applied to the controllers in our web application.
 

Spring’s @ControllerAdvice annotation may be a specialised variety of @Component that exists to handle cross cutting issues for controllers.
The most common use case is to produce exception handlers, however it will do a number of different neat things also.
It can for example intercept the responses from controllers. In this post I will focus on Exception Handling.

 

From Spring three we can have a mechanism to handle this scenario. We can write one global exception handling code to cater to all needs of handling all exceptions in the applications.
 

This annotation will apply, by default, to all the classes with the @Controller annotation (which extends to @RestController). You can configure it to use multiple packages those can also be chosen by following mechanism.
 

@ControllerAdvice("com.example.controller")
 @ControllerAdvice(value = "com.example.controller")
 @ControllerAdvice(basePackages = "com.example.controller")

@ExceptionHandler is associate annotation for handling exceptions in specific handler classes or handler strategies. In Servlet environments, we are able to combine the @ExceptionHandler annotation with @ResponseStatus to outline the response status for the hypertext transfer protocol response.

If you're not exploitation the @ControllerAdvice annotation, then the code for handling those exceptions would be among the controller itself, that clearly add some duplication and muddle to the class.
By using @ControllerAdvice along with @ExceptionHandler allows you to prevent this by providing globle error handling and more specifically.

Generate a new class which is able to extends from ResponseEntityExceptionHandler and add following code to that.
Don't forget to add @ControllerAdvice on it.

@RestControllerAdvice
public class GlobalExceptionHandeler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(AuthenticationException.class)
    public static ResponseEntity<Object> generateAuthExceptionResponse(AuthenticationException exception) {
        return new ResponseEntity<Object>(ResponseGenerator.generateExceptionResponse(exception, exception.getMessage(),
                null, HttpStatus.UNAUTHORIZED), HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(UserException.class)
    public static ResponseEntity<ResponseDTO> generateUserExceptionResponse(UserException exception) {
        return new ResponseEntity<>(ResponseGenerator.generateExceptionResponse(exception, exception.getMessage(),
                exception.getMessageParam(), HttpStatus.BAD_REQUEST), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(CurrencyException.class)
    public static ResponseEntity<ResponseDTO> generateCurrencyExceptionResponse(CurrencyException exception) {
        return new ResponseEntity<>(ResponseGenerator.generateExceptionResponse(exception, exception.getMessage(),
                exception.getMessageParam(), HttpStatus.BAD_REQUEST), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public static ResponseEntity<ResponseDTO> generateExceptionResponse(Exception exception) {
        return new ResponseEntity<>(ResponseGenerator.generateExceptionResponse(exception, exception.getMessage(),
                null, HttpStatus.BAD_REQUEST), HttpStatus.BAD_REQUEST);
    }
}

 

thanks.

About Author

Author Image
Avnish Yadav

Avnish is a Software Developer having knowledge of java , j2ee ,sql , javascript and Data Structure.

Request for Proposal

Name is required

Comment is required

Sending message..