使用 @Validated ,@Valid ,@NotBlank 之類的,請自行百度,本文着重與捕捉校驗失敗信息並封裝返回出去java
參考:app
https://mp.weixin.qq.com/s/EaZxYKyC4L_EofWdtyBCpwide
https://www.jianshu.com/p/bcc5a3c86480ui
捕捉校驗失敗異常信息spa
@ControllerAdvice public class WebExceptionHandler {
//處理Get請求中 使用@Valid 驗證路徑中請求實體校驗失敗後拋出的異常,詳情繼續往下看代碼 @ExceptionHandler(BindException.class) @ResponseBody public ResponseVO BindExceptionHandler(BindException e) { String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining()); return new ResponseVO(message); } //處理請求參數格式錯誤 @RequestParam上validate失敗後拋出的異常是javax.validation.ConstraintViolationException @ExceptionHandler(ConstraintViolationException.class) @ResponseBody public ResponseVO ConstraintViolationExceptionHandler(ConstraintViolationException e) { String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining()); return new ResponseVO(message); } //處理請求參數格式錯誤 @RequestBody上validate失敗後拋出的異常是MethodArgumentNotValidException異常。 @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public ResponseVO MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) { String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining()); return new ResponseVO(message); } }
以下示例請求參數報錯的話,會拋出 BindException 而不是 ConstraintViolationException 和 MethodArgumentNotValidExceptioncode
@RestController @RequestMapping("test") public class TestController { @GetMapping("refund") public ResponseVO refund(@Valid RefundRequest request) throws Exception { return new ResponseVO(); } } @Data public class RefundRequest implements Serializable { @NotBlank(message = "訂單號不能爲空") private String orderId; @Min(value = 0, message = "已消費金額金額不能爲負數") private int orderAmt; }
若是多個請求參數都校驗失敗,則遇到第一個校驗失敗就拋出異常,接下來的異常參數不作校驗,配置以下blog
@Configuration public class WebConfig { @Bean public Validator validator() { ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class) .configure() //failFast的意思只要出現校驗失敗的狀況,就當即結束校驗,再也不進行後續的校驗。 .failFast(true) .buildValidatorFactory(); return validatorFactory.getValidator(); } @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor(); methodValidationPostProcessor.setValidator(validator()); return methodValidationPostProcessor; } }