捕获HttpMessageNotReadableException,JsonMappingException

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Numeric value (123121231231231233131231331) out of range of long; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Numeric value (123121231231231233131231331) out of range of long

实体类属性设置是Long类型,传入的参数超过Long的最大长度,抛出HttpMessageNotReadableException。

用Hibernate-Validator中的注解无法处理这种异常,所以需要自定义注解去处理。

在全局异常类中对HttpMessageNotReadableException进行处理,其中还嵌套了一个JsonMappingException异常,所以还要对这个异常进行处理。

代码如下

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonFormatVaild {
    String message() default "";
}   


@ExceptionHandler(value = HttpMessageNotReadableException.class)
    public ApiResponse httpMessageNotReadableException(HttpMessageNotReadableException e) {
        // 打印堆栈信息
        log.error(ThrowableUtil.getStackTrace(e));
        String erroMessage = null;
        Throwable cause = e.getCause();
        if (cause instanceof JsonMappingException) {
            List<JsonMappingException.Reference> list = ((JsonMappingException) cause).getPath();
            for (JsonMappingException.Reference r : list) {
                Object object = r.getFrom();
                Class<?> c = object.getClass();
                String fieldName = r.getFieldName();
                Field field;
                try {
                    field = c.getDeclaredField(fieldName);
                    JsonFormatVaild jsonFormatVaild = field.getDeclaredAnnotation(JsonFormatVaild.class);
                    erroMessage = jsonFormatVaild.message();
                } catch (NoSuchFieldException noSuchFieldException) {
                    noSuchFieldException.printStackTrace();
                }
                if (erroMessage != null) {
                    break;
                }
            }
        }
        return buildResponseEntity(ResultCodeEnum.PARAM_ERROR.getCode(), erroMessage);
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值