@Valid @RestControllerAdvice 一起使用返回统一校验格式

@Valid @RestControllerAdvice 一起使用返回统一校验格式

自定义异常类


/**
 * 自定义异常类
 * @author luwang
 *
 */
public class ControllerException extends RuntimeException {
    private static final long serialVersionUID = -111111;
    protected HttpStatus statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
	private String errorMessage;
	private  String errorCode; 
}

定义ValidationError

public class ValidationError {
    private static final long serialVersionUID = -111111;
	private String errorMessage;
	private  String errorCode; 
}

定义 GlobalDefultExceptionHandler


@RestControllerAdvice
public class GlobalDefultExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ValidationError handleValidationBodyException(MethodArgumentNotValidException e) {
        for (ObjectError s : e.getBindingResult().getAllErrors()) {
            return new ValidationError("Invalid_Request_Parameter", s.getObjectName() + ": " + s.getDefaultMessage());
        }
        return new ValidationError("Invalid_Request_Parameter", "未知参数错误");
    }
    @ExceptionHandler(ControllerException.class)
    public ValidationError handleUnProccessableServiceException(ControllerException e, HttpServletResponse response) {
        response.setStatus(e.getStatusCode().value());

        return new ValidationError(e.getErrorCode(), e.getMessage());
    }
}

定义FieldCheckConfig

@Component
public class FieldCheckConfig {
    @Resource
    private LocalValidatorFactoryBean localValidatorFactoryBean;
    public FieldCheckConfig() {
    }

    public void check(BaseRq request) throws ControllerException {
        Set<ConstraintViolation<BaseRq>> validErrors = this.localValidatorFactoryBean.validate(request, new Class[]{Default.class});
        Iterator iterator = validErrors.iterator();
        ActionLog logContent = new ActionLog();

        while(iterator.hasNext()) {
            ConstraintViolation constraintViolation = (ConstraintViolation)iterator.next();
            String error = constraintViolation.getMessage();
            if (StringUtils.isNotNull(error)) {
                String  message="";
                String code="";
                String[] args = error.split(":");
                if (args.length == 2) {
                    code=args[0];
                    message=args[1];
                }
                throw new ControllerException(code, message);
            }
        }

    }
}

定义请求bean


public  class BaseRq implements Serializable {
	private static final long serialVersionUID = 2765678429008175088L;
}

@Valid
public class DemonQueryRqDto extends BaseRq implements Serializable {
    private static final long serialVersionUID = -4822849672901323609L;
    @NotEmpty(message = "0001:userName Not Empty")
    private String userName;
    @Pattern(regexp ="^[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\\s+(20|21|22|23|[0-1]\\d):[0-5]\\d:[0-5]\\d$", message = "datetime not Pattern")
    private String datetime;

具体使用


@RestController
@RequestMapping(value ="/demo/demonQuery", method = RequestMethod.POST)
public class DemonQuery {
    private final FieldCheckConfig fieldCheckUtil;
    public DemonQuery(FieldCheckConfig fieldCheckUtil) {
        this.fieldCheckUtil = fieldCheckUtil;
    }


    @RequestMapping("/getDemon")
    public DemonQueryRsDto getDemon(@RequestBody DemonQueryRqDto rq) throws ControllerException
    {
        fieldCheckUtil.check(rq);
        DemonQueryRsDto demonQueryRsDto=new DemonQueryRsDto();
        demonQueryRsDto.setUserName(rq.getUserName());
        return demonQueryRsDto;
    }

    @RequestMapping("/getDemonEp1")
    public DemonQueryRsDto getDemonEp1(@RequestBody DemonQueryRqDto rq) throws ControllerException
    {
        fieldCheckUtil.check(rq);
        throw new ControllerException("0001","asdfasd");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值