【问题标题】:How to handle @Valid violations in the RequestMapping?如何处理 RequestMapping 中的 @Valid 违规?
【发布时间】:2018-08-17 13:41:01
【问题描述】:

我在 Java/Spring 中有以下 Rest Controller。检查约束的验证。然而,这些都是在它到达我的'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();
    }

}

【问题讨论】:

标签: java spring rest validation


【解决方案1】:

你应该使用 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)
    }
}

它允许处理控制器抛出的异常,包括验证异常。

【讨论】:

    【解决方案2】:

    您可以将 BindingResult 作为参数添加到方法签名的末尾。

    @RequestMapping(value = "bar", method = RequestMethod.POST)
    public ResponseEntity<Void> bar(@RequestBody @Valid Foo foo, BindingResult bindingResult) 
    {
        if (bindingResult.hasErrors()) {
            //do something if errors occured
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        } 
    
        //body part
        return ResponseEntity.status(HttpStatus.OK).build();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多