如何处理RequestMapping中的@Valid违规?

我在 Java/Spring 中有以下 Rest 控制器。检查约束的验证。但是,这些在到达我的 'bar' 方法的主体之前就已完成。如何处理违规案件?我可以自定义 400 响应正文吗?


@RestController

@RequestMapping("foo")

public class FooController {


    @RequestMapping(value = "bar", method = RequestMethod.POST)

    public ResponseEntity<Void> bar(@RequestBody @Valid Foo foo) {

        //body part

        return ResponseEntity.status(HttpStatus.OK).build();

    }


}


偶然的你
浏览 124回答 2
2回答

FFIVE

您应该使用 controllerAdvice,这是一个示例(在 kotlin 中):@ControllerAdviceopen class ExceptionAdvice {&nbsp; &nbsp; @ExceptionHandler(MethodArgumentNotValidException::class)&nbsp; &nbsp; @ResponseBody&nbsp; &nbsp; @ResponseStatus(HttpStatus.BAD_REQUEST)&nbsp; &nbsp; open fun methodArgumentNotValidExceptionHandler(request: HttpServletRequest, e: MethodArgumentNotValidException): ErrorDto {&nbsp; &nbsp; &nbsp; &nbsp; val errors = HashMap<String, String>()&nbsp; &nbsp; &nbsp; &nbsp; for (violation in e.bindingResult.allErrors) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (violation is FieldError) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errors.put(violation.field, violation.defaultMessage)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return ErrorDto(errors)&nbsp; &nbsp; }&nbsp; &nbsp; @ExceptionHandler(BindException::class)&nbsp; &nbsp; @ResponseBody&nbsp; &nbsp; @ResponseStatus(HttpStatus.BAD_REQUEST)&nbsp; &nbsp; open fun bindExceptionHandler(request: HttpServletRequest, e: BindException): ErrorDto {&nbsp; &nbsp; &nbsp; &nbsp; val errors = HashMap<String, String>()&nbsp; &nbsp; &nbsp; &nbsp; for (violation in e.bindingResult.allErrors) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (violation is FieldError) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errors.put(violation.field, violation.defaultMessage)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return ErrorDto(errors)&nbsp; &nbsp; }}它允许处理控制器抛出的异常,包括验证异常。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java