【发布时间】:2018-05-17 19:02:27
【问题描述】:
我已经尝试了what is the right way to handle errors in spring-webflux 中建议的所有 3 种解决方案,但 WebExceptionHandler 没有被调用。我正在使用Spring Boot 2.0.0.M7。 Github 仓库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()
【问题讨论】:
-
有人知道如何轻松创建 WebExchangeBindException 吗?
标签: spring-boot exception-handling reactive-programming spring-webflux