@ControllerAdvice 全域性校驗異常處理
阿新 • • 發佈:2018-12-07
舊版SpringMVC中的控制器引數校驗:
@ControllerAdvice
public class ControllerCheckAdvice {
private Logger log = LoggerFactory.getLogger(getClass());
@ExceptionHandler(BindException.class)
public ResponseEntity<Tip> checkRequest(BindException e) {
log. info(e.getMessage());
BindingResult bindingResult = e.getBindingResult();
String errorMesssage = "校驗失敗:";
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMesssage += fieldError.getField() + ":" + fieldError.getDefaultMessage () + ";";
}
Tip tip = new ErrorTip(400, errorMesssage.substring(0, errorMesssage.length() - 1));
return ResponseEntity.badRequest().body(tip);
}
}
新版WebFlux異常校驗
@ControllerAdvice
public class ControllerCheckAdvice {
private Logger log = LoggerFactory.getLogger(getClass());
@ExceptionHandler(WebExchangeBindException.class)
public ResponseEntity<Tip> checkRequest(BindException e) {
log.info(e.getMessage());
BindingResult bindingResult = e.getBindingResult();
String errorMesssage = "校驗失敗:";
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMesssage += fieldError.getField() + ":" + fieldError.getDefaultMessage() + ";";
}
Tip tip = new ErrorTip(400, errorMesssage.substring(0, errorMesssage.length() - 1));
return ResponseEntity.badRequest().body(tip);
}
}