我的应用程序是由Spring Boot 2 webflux和thymeleaf制作的,我想捕获所有异常并将错误呈现到自定义的错误页面。
我使用@ControllerAdvice和@ExceptionHandler来捕获异常并在中央处理错误,我只能处理控制器中抛出的所有异常,但是我无法捕获那些映射错误(内容协商和HTTP映射错误),例如UnsupportedMediaTypeStatusException。我搜索发现这是一个已知问题(https://github.com/spring-projects/spring-framework/issues/21097#issuecomment-453468295)。
如果使用WebMvc,则不会出现此类问题,所有异常都可以捕获。我的问题是如何捕获所有异常并在webflux中显示我自己的错误页面。
这里是简短代码:
@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);
}
}