Spring 5 Reactive - WebExceptionHandler 没有被调用

2023-12-19

我已经尝试了中建议的所有 3 个解决方案处理 spring-webflux 中的错误的正确方法是什么 https://stackoverflow.com/questions/43575538/what-is-the-right-way-to-handle-errors-in-spring-webflux/45280499#45280499, but WebExceptionHandler没有接到电话。我在用Spring Boot 2.0.0.M7。 Github 仓库here https://github.com/legendjaks/reflux

@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()
  }
}

UPDATE:

当我将 Spring Boot 版本更改为2.0.0.M2, the WebExceptionHandler正在接到电话。我需要做点什么吗2.0.0.M7?

解决方案:

根据布莱恩的建议,它的工作原理是

@Bean
@Order(-2)
fun globalErrorHandler() = GlobalErrorHandler()

您可以提供自己的WebExceptionHandler,但你必须相对于其他人来订购它,否则他们可能会在你有机会尝试之前处理错误。

  • the DefaultErrorWebExceptionHandlerSpring Boot 提供的错误处理功能(请参阅参考文档 https://docs.spring.io/spring-boot/docs/2.0.0.M7/reference/html/boot-features-developing-web-applications.html#boot-features-webflux-error-handling)订购于-1
  • the ResponseStatusExceptionHandlerSpring Framework 提供的订购地址为0

所以你可以添加@Order(-2)在您的错误处理组件上,将其排序在现有组件之前。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring 5 Reactive - WebExceptionHandler 没有被调用 的相关文章

随机推荐