1

In my Spring Webflux application I have a @ControllerAdvice annotated class that implements WebExceptionHandler, with its @Order set to -2, and my idea is for it to be a global exception handler.

In this class I check the type of the Throwable received and handle it in the appropriate way, like this:

@Component
@Slf4j
@Order(-2)
@ControllerAdvice
public class CustomWebExceptionHandler implements WebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
           if (ex instanceof ResponseStatusException) {
                ... do something
           }
           if (ex instanceof DomainException) {
                ... do something else
           }
}

In one of these "... do something" blocks I've made a mistake and an IllegalArgumentException was thrown. I thought it would be handled by this same class but it ended up being handled by the DefaultErrorWebExceptionHandler, that has @Order(-1).

My question is: is it possible to have this IllegalArgumentException be handled by my CustomWebExceptionHandler instead?

1 Answers1

0

I think you don't need order here unless you have multiple handlers. From the code above I see that you have a CustomWebExceptionHandler annotated with ControllerAdvice. By default the methods in an @ControllerAdvice apply globally to all Controllers. Now to catch all exceptions thrown by those targeted controllers you can just simply define a method with @ExceptionHandler with throwable as parameter, something like this shall work for you:

    @ControllerAdvice
    public class CustomWebExceptionHandler {
        @ExceptionHandler
        public ResponseEntity handleExceptions(Throwable ex)
        {
           if (ex instanceof ResponseStatusException) {
                ... do something
           }
           if (ex instanceof DomainException) {
                ... do something else
           }
        }
    }

You can have multiple Exception handlers(per exception) if you wish see detailed answer here Setting Precedence of Multiple @ControllerAdvice @ExceptionHandlers.

ravinikam
  • 3,666
  • 6
  • 28
  • 25