4

My application is made by Spring Boot 2 webflux and thymeleaf, I want to catch all the exception and render the error to a customized error page.

I use @ControllerAdvice and @ExceptionHandler to catch exceptions and handle errors in a central place, I can only handle all the exceptions which are thrown in my controller, but I cannot catch those mapping errors (content negotiation and HTTP mapping errors) such as UnsupportedMediaTypeStatusException. I searched and find this is a known issue (https://github.com/spring-projects/sprienter code hereng-framework/issues/21097#issuecomment-453468295).

If I use WebMvc, there is no this kind of problem, all exceptions can be caught. My question is how to catch all the exceptions and show my own error page in webflux.

Here is the brief code:

@ControllerAdvice
@Slf4j
public class DefaultExceptionHandlers {
    // works OK for my own thrown exception
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = CustomException1.class)
    public Mono<String> handleCustom1Exceptions(CustomException1 e) {
        return Mono.just("error1");
    }

    // works OK for my own thrown exception
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = CustomException2.class)
    public Mono<String> handleCustom2Exceptions(CustomException2 e) {
        return Mono.just("error2);
    }

    // This exception handler is not called at all for the exceptions which are thrown by spring framework
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = Exception.class)
    public Mono<String> handleAllExceptions(Exception e) {
        return Mono.just("error3);
    }
}
user2592010
  • 41
  • 1
  • 3
  • Can you show your exception handler code? – wjans Feb 06 '20 at 06:35
  • Use a WebExceptionHandler, check this section: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/web-reactive.html#webflux-exception-handler – dbustamante Oct 15 '20 at 23:14

0 Answers0