1. 程式人生 > >@ControllerAdvice 全域性校驗異常處理

@ControllerAdvice 全域性校驗異常處理

舊版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); } }