2 回答
TA贡献1797条经验 获得超6个赞
您应该使用 controllerAdvice,这是一个示例(在 kotlin 中):
@ControllerAdvice
open class ExceptionAdvice {
@ExceptionHandler(MethodArgumentNotValidException::class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
open fun methodArgumentNotValidExceptionHandler(request: HttpServletRequest, e: MethodArgumentNotValidException): ErrorDto {
val errors = HashMap<String, String>()
for (violation in e.bindingResult.allErrors) {
if (violation is FieldError) {
errors.put(violation.field, violation.defaultMessage)
}
}
return ErrorDto(errors)
}
@ExceptionHandler(BindException::class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
open fun bindExceptionHandler(request: HttpServletRequest, e: BindException): ErrorDto {
val errors = HashMap<String, String>()
for (violation in e.bindingResult.allErrors) {
if (violation is FieldError) {
errors.put(violation.field, violation.defaultMessage)
}
}
return ErrorDto(errors)
}
}
它允许处理控制器抛出的异常,包括验证异常。
添加回答
举报