我正在使用@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/