私のアプリケーションは Spring Boot 2 の webflux と thymeleaf で作成されています。すべての例外をキャッチして、エラーをカスタマイズされたエラー ページに表示したいと考えています。
@ControllerAdvice と @ExceptionHandler を使用して、例外をキャッチし、中央の場所でエラーを処理します。コントローラーでスローされたすべての例外しか処理できませんが、UnsupportedMediaTypeStatusException などのマッピング エラー (コンテンツ ネゴシエーションと HTTP マッピング エラー) をキャッチできません。 . 検索したところ、これは既知の問題です ( https://github.com/spring-projects/sprienter code here
ng-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);
}
}