spring - 如何从Spring Webflux Controller 捕获异常?

标签 spring kotlin spring-webflux

我正在使用@Valid @RequestBody在 Controller 中使用javax验证。当服务器接收到无效数据时,它将引发错误,但是我想处理该错误并返回自定义格式的错误。我无法在 Controller 建议中捕获异常。我正在使用spring webFlux,所以不能使用bindingResult。我该如何处理该异常?这是我的代码

控制者

    @PostMapping
    fun createPerson(@Valid @RequestBody resource: PersonResource): Mono<Person> {
        return personService.save(resource.toPerson())
    }

资源资源
data class PersonResource(
    val id: String?,

    @field:NotEmpty
    val name: String,
    ...
}

错误处理程序
@ControllerAdvice
class ApiErrorHandler {
  @ExceptionHandler(IllegalArgumentException::class)
    fun handleValidationErrors(e: IllegalArgumentException): ResponseEntity<*> {
    // never reaches here
  }
}

最佳答案

我认为您正在捕获另一个异常(exception)。我正在使用@ControllerAdvice捕获 WebExchangeBindException 作为验证错误,它对我有用。

A specialization of ServerWebInputException thrown when after data binding and validation failure. Implements BindingResult (and its super-interface Errors) to allow for direct analysis of binding and validation errors.

关于spring - 如何从Spring Webflux Controller 捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51126888/

相关文章:

java - 如何在不迭代 List<Map> 的情况下获取值

java - 使用 Spring 框架单例 bean 进行单元测试

java - 请求 Spring Cloud Gateway 中 GlobalFilter 中的其他服务

java - onErrorResume 运算符会忽略 flatMap 中抛出的异常

java - 使用当前年份的 JPA/Hibernate 主键值序列

javassist,获取doGet方法的第二个参数

android - 排序嵌套列表对象

java - Gradle 迁移 3.1.4 -> 3.5.1; :app module doesn't compile; ClassNotFoundException: Didn't find class on path: DexPathList

jdbc - Micronaut 数据 jdbc : saving an existing entity creates a new entity instead of updating the existing one

java - Spring Web Reactive 不能作为部署在 Tomcat 8.5 上的 war 文件工作