using @ControllerAdvice exception handler as a standalone library

143 views Asked by At

I want to create a standalone Spring library that handles standard api exceptions via @ControllerAdvice. My approach is to make it easy to use in different modules without any additional configuration.

There is a code of my exception handler:

@ControllerAdvice
public class ApiErrorControllerAdvice extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {ApiErrorException.class})
    public ResponseEntity<ErrorResponseTo> handleApiErrorException(ApiErrorException apiError) {
        return new ResponseEntity<>(
                new ErrorResponseTo(apiError.getMessage()),
                apiError.getHttpStatus()
        );
    }
}

How should I configure my application to make exception handler automatically picked up by Spring?

1

There are 1 answers

0
Mohamed El-Harrougui On BEST ANSWER
  • The @ControllerAdvice annotation marks the class as a global exception handler.
  • The @ExceptionHandler(Exception.class) annotation on the handleApiErrorException method specifies that this method will handle exceptions of type ApiErrorException.
  • You can add more @ExceptionHandler methods for handling specific exceptions. And you can also add a general @ExceptionHandler(Exception.class) method to handle all types of Exceptions.
  • Ensure that your @ControllerAdvice class is within the package or subpackage that is scanned by your Spring application. If it's in a different package, you might need to use the basePackages attribute of @ComponentScan in your main application class @ComponentScan(basePackages = "com.example"), or specify the package in the @ControllerAdvice annotation.