【发布时间】:2022-02-09 13:03:02
【问题描述】:
当从WebFilter 链抛出错误时,如何在 WebFlux 中全局拦截和处理错误?
如何处理控制器抛出的错误很清楚:@ControllerAdvice 和 @ExceptionHandler 帮助很大。
当WebFilter 组件抛出异常时,此方法不起作用。
在以下配置中,GET /first 和 GET /second 响应故意引发抛出异常。尽管@ExceptionHandler 方法handleFirst、handleSecond 是相似的,但永远不会调用handleSecond。我想这是因为MyWebFilter 不会让ServerWebExchange 进入可以应用GlobalErrorHandlers 方法的阶段。
回复GET /first:
HTTP 500 "hello first" // expected
HTTP 500 "hello first" // actual
回复GET /second:
HTTP 404 "hello second" // expected
HTTP 500 {"path": "/second", "status": 500, "error": "Internal Server Error" } // actual
@RestController
class MyController {
@GetMapping("/first")
String first(){
throw new FirstException("hello first");
}
}
@Component
class MyWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange swe, WebFilterChain wfc) {
var path = swe.getRequest().getURI().getPath();
if (path.contains("second")){
throw new SecondException("hello second")
}
}
}
@ControllerAdvice
class GlobalErrorHandlers {
@ExceptionHandler(FirstException::class)
ResponseEntity<String> handleFirst(FirstException ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.message)
}
@ExceptionHandler(SecondException::class)
ResponseEntity<String> handleSecond(SecondException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.message)
}
}
【问题讨论】:
-
它就像所有应用程序一样,要么在过滤器中处理它,要么在前面有一个过滤器来捕获所有抛出的异常。
-
你可能想看看WebExceptionHandler
标签: spring exception spring-webflux