捕获HttpMessageNotReadableException,JsonMappingException
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Numeric value (123121231231231233131231331) out of range of long; nested exception is com.fasterxml.jackson.databi
·
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);
}
更多推荐
已为社区贡献1条内容
所有评论(0)