Springboot处理实体类参数校验异常

1.实体类校验

package com.imooc.mall.model.request;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * 商品目录添加请求类
 */
public class AddCategoryReq {
    @NotNull(message = "name不能为null")
    @Size(min = 2,max = 5)
    private String name;
    @NotNull(message = "type不能为null")
    @Max(3)
    private Integer type;
    @NotNull(message = "parentId不能为null")
    private Integer parentId;
    @NotNull(message = "orderNum不能为null")
    private Integer orderNum;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

   

2.参数校验异常统一返回

/**
 * 全局处理统一异常,包括业务层用ApiResponse统一格式返回处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 /**
     * 处理参数校验异常
     *
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiRestResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("MethodArgumentNotValidException: " + e);
        //返回时,调用下面一个方法来处理异常,e.getBindingResult()作为参数传入
        return handleBindingResult(e.getBindingResult());
    }
    private ApiRestResponse handleBindingResult(BindingResult result){
        //把异常处理为对外暴露的提示
        //list定义为null时,还没有初始化,没有在堆内还没有地址,不能直接add();
        //要先new
        List list = new ArrayList<>();
        if (result.hasErrors()) {
            List allErrors = result.getAllErrors();
            for (ObjectError objectError:
                    allErrors
                 ) {
                String message = objectError.getDefaultMessage();
                list.add(message);

            }
        }
         if (list == null) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR);
        }
        return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR.getStatus(), list.toString());
    }
}

你可能感兴趣的:(java,实体类参数校验异常处理)