美文网首页
@Valid @RequestBody参数异常处理类

@Valid @RequestBody参数异常处理类

作者: 晚风吹___ | 来源:发表于2020-07-01 15:45 被阅读0次
    import com.example.demo.pojo.ErrorMsg;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.FieldError;
    import org.springframework.validation.ObjectError;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @Author 
     * @Date: 
     */
    @ControllerAdvice
    public class ExceptionHandlerContrller {
    
    
        @ExceptionHandler(MethodArgumentNotValidException.class)
        @ResponseBody
        public List<ErrorMsg> exception(MethodArgumentNotValidException e) {
            BindingResult bindingResult = e.getBindingResult();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            List<ErrorMsg> errorMsgs = new ArrayList<>();
    
            allErrors.forEach(objectError -> {
                ErrorMsg errorMsg = new ErrorMsg();
                FieldError fieldError = (FieldError)objectError;
                errorMsg.setField(fieldError.getField());
                errorMsg.setObjectName(fieldError.getObjectName());
                errorMsg.setMessage(fieldError.getDefaultMessage());
                errorMsgs.add(errorMsg);
            });
            return errorMsgs;
        }
    }
    

    相关文章

      网友评论

          本文标题:@Valid @RequestBody参数异常处理类

          本文链接:https://www.haomeiwen.com/subject/nqfhqktx.html