问题
前端传Json格式数据到后台后,springmvc报
org.springframework.http.converter.HttpMessageNotReadableException:
* JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token;
* nested exception is com.fasterxml.jackson.databind.JsonMappingException:
* Can not deserialize instance of java.lang.String out of START_OBJECT token
* at [Source: java.io.PushbackInputStream@6822f8aa; line: 1, column: 88] (through reference chain: com.xxx.XXXDto["employees"])
方案
我们要解决这个问题,可以使用Spring中的统一异常处理方式 里面介绍的一种
@ExceptionHandler({HttpMessageNotReadableException.class, JsonMappingException.class, HttpMediaTypeNotSupportedException.class})
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String,Object> exceptionHandler(Exception ex){
Map<String,Object> map = new HashMap<>(3);
try{
map.put("code","400");
map.put("msg",ex.getMessage());
return map;
}catch (Exception e){
log.error("exception handler error",e);
map.put("code","400");
map.put("msg",e.getMessage());
return map;
}
}
解决过程遇到的问题
上面方法虽然能够处理JSON格式错误的问题,但是返回给前端的数据内容就是下面格式
JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: java.io.PushbackInputStream@6822f8aa; line: 1, column: 88] (through reference chain: com.xxx.XXXDto["callBackUrl"])
一眼看不到是什么问题,就算是熟悉了这个错误,也不能马上找到是哪个地方出的问题,因为我们需要对上面的数据进行加工后再返回给前端
最终解决问题
我们debug源码发现,改异常是在springframework的org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter
里面抛出的
异常是JsonMappingException extends JsonProcessingException
,springmvc里抛出了HttpMessageNotReadableException
,因此,我们只需要在统一异常处理的地方添加对应处理逻辑,就可以友好返回给前端
@ExceptionHandler({HttpMessageNotReadableException.class, JsonMappingException.class, HttpMediaTypeNotSupportedException.class})
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String,Object> exceptionHandler(Exception ex){
Map<String,Object> map = new HashMap<>(3);
try{
if(ex instanceof HttpMessageNotReadableException
&& ex.getMessage().indexOf("JSON parse error:")>-1){
map.put("code","400");
String message=ex.getMessage();
int beginIndex=message.indexOf("XXXDto[\"");
int endIndex=message.indexOf("\"])",beginIndex);
message="参数"+message.substring(beginIndex+22,endIndex)+" 格式错误";
map.put("msg",message);
}else{
map.put("code","400");
map.put("msg",ex.getMessage());
}
return map;
}catch (Exception e){
log.error("exception handler error",e);
map.put("code","400");
map.put("msg",e.getMessage());
return map;
}
}