@Valid 注解校验数字转化异常提示消息更改

        当项目中使用 @Valid 对表单进行校验,对Integer 类型校验的最小值、最大值等都无法避免对该类型输入字符串的错误提示,即向前端返回数字转化异常的明文代码,对用户的显示特别不友好。

        通过设置全局异常捕获机制,将 BindException进行捕获,若异常类型为数字转化异常,即提示该字段格式不正确。

    @ExceptionHandler(value = ConstraintViolationException.class)
    public ServerResponse ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        List<String> msgList =  ex.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        return ServerResponse.createByErrorMessage(msgList.toString());
    }

    @ExceptionHandler(value = BindException.class)
    public ServerResponse BindExceptionHandler(BindException ex) {
        String msgList =  ex.getFieldErrors()
                .stream()
                .map(fieldError -> {
                    Field field = ReflectionUtils.findField(FieldError.class, "source");
                    field.setAccessible(true);
                    Object source = ReflectionUtils.getField(field, fieldError);
                    if (source instanceof TypeMismatchException) {
                        TypeMismatchException mismatchException = (TypeMismatchException) source;
                        source = mismatchException.getPropertyChangeEvent().getSource();
                        if (mismatchException.getCause() instanceof NumberFormatException) {
                            field = ReflectionUtils.findField(source.getClass(), fieldError.getField());
                            ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
                            return apiModelProperty == null?"":apiModelProperty.value() + "格式不正确";
                        }
                    }
                    return fieldError.getDefaultMessage();
                }
                ).collect(Collectors.joining("、","您填写的信息共有"+ex.getFieldErrors().size()+"项错误:",""));
        return ServerResponse.createByErrorMessage(msgList);
    }
 
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值