为什么Spring为JSON抛出具有不同原因的HttpMessageNodeReadableException
我有一个异常处理程序控制器,我在其中捕获HttpMessageTreadableException,如下所示:为什么Spring为JSON抛出具有不同原因的HttpMessageNodeReadableException,json,spring,spring-mvc,jackson,Json,Spring,Spring Mvc,Jackson,我有一个异常处理程序控制器,我在其中捕获HttpMessageTreadableException,如下所示: @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody protected ErrorMessage handleJsonException(final HttpMessageNot
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
protected ErrorMessage handleJsonException(final HttpMessageNotReadableException ex, final HttpServletRequest request)
{
if (ex.getCause() instanceof JsonParseException)
{
// some code
}
if (ex .getCause() instanceof JsonMappingException)
{
// some code
}
}
对于格式错误的JSON,POST和PUT有不同的原因。JSON文本中缺少第一个双引号
{firstName":"abc","lastName":"xyz"}
POST-JsonParseException
PUT-JsonMappingException
我认为这两种方法都应该有相同的原因JsonParseException,因为语法是错误的
有谁能解释一下为什么spring将不同的for PUT作为JsonMappingException进行处理。为了解决这类问题,我找到了这篇文章-> 它有一些解决方法,比如使用GetMostSpecificCase。我正在读它来解决我的问题。试试这个 //ex->HttpMessageTreadableException
Throwable throwable = ex.getCause();
JsonMappingException jsonMappingException = ((JsonMappingException) throwable);
// import 'InvalidFormatException' from com.fasterxml.jackson.databind.exc package
List<JsonMappingException.Reference> references = ((InvalidFormatException)throwable).getPath();
for (JsonMappingException.Reference reference : references) {
if (reference.getFieldName() != null) {
field += reference.getFieldName() + ".";
}
}
String message = jsonMappingException.getOriginalMessage();