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);
    }

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐