spring-boot - Spring 5 Reactive - WebExceptionHandler 没有被调用

标签 spring-boot exception-handling reactive-programming spring-webflux

我已经尝试了 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/

相关文章:

unit-testing - 不可能对 Spring Data JPA @Query 进行单元测试,真的吗?

java - spring cloud stream rabbit 的退避设置

php - 如果 $model->save() 失败,则继续代码

system.reactive - 是否有 Rx 运算符用于仅在流 2 发出事物时组合来自流 1 和 2 的最新数据?

.net - Rx 与响应式编程有什么关系?

javascript - 可观察异步的 rxJs 回调

spring - 获取我的 REST API 文档的 Spring Boot Swagger 配置有什么问题?为什么我无法访问文档?

java - 如何动态自动连接服务

c# - 保存 XDocument 时会发生什么异常?

javascript - 如何在不触发错误的情况下检测 iframe 是否可访问?