我已经尝试了 what is the right way to handle errors in spring-webflux 中建议的所有 3 种解决方案,但是 WebExceptionHandler
没有被调用。我正在使用 Spring Boot 2.0.0.M7
。 Github repo here
@Configuration
class RoutesConfiguration {
@Autowired
private lateinit var testService: TestService
@Autowired
private lateinit var globalErrorHandler: GlobalErrorHandler
@Bean
fun routerFunction():
RouterFunction<ServerResponse> = router {
("/test").nest {
GET("/") {
ServerResponse.ok().body(testService.test())
}
}
}
}
@Component
class GlobalErrorHandler() : WebExceptionHandler {
companion object {
private val log = LoggerFactory.getLogger(GlobalErrorHandler::class.java)
}
override fun handle(exchange: ServerWebExchange?, ex: Throwable?): Mono<Void> {
log.info("inside handle")
/* Handle different exceptions here */
when(ex!!) {
is ClientException -> exchange!!.response.statusCode = HttpStatus.BAD_REQUEST
is Exception -> exchange!!.response.statusCode = HttpStatus.INTERNAL_SERVER_ERROR
}
return Mono.empty()
}
}
更新:
当我将 Spring Boot 版本更改为 2.0.0.M2
时,将调用 WebExceptionHandler
。我需要为 2.0.0.M7
做些什么吗?
解决方案:
按照布赖恩的建议,它起到了作用
@Bean
@Order(-2)
fun globalErrorHandler() = GlobalErrorHandler()
最佳答案
您可以提供自己的 WebExceptionHandler
,但您必须相对于其他人对其进行排序,否则他们可能会在您有机会尝试之前处理错误。
- Spring Boot 提供的用于错误处理的
DefaultErrorWebExceptionHandler
(see reference documentation) 排序在-1
- Spring Framework提供的
ResponseStatusExceptionHandler
排序在0
因此,您可以在错误处理组件上添加 @Order(-2)
,以便在现有组件之前对其进行排序。
关于spring-boot - Spring 5 Reactive - WebExceptionHandler 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47631243/