Jackson deserialization error handling

后端 未结 4 1776
情话喂你
情话喂你 2020-12-13 10:15

My problem is fairly simple : I have the following simple class:

public class Foo {
   private int id = -1;
   public void setId(int _id){ this.id = _id; }
          


        
4条回答
  •  Happy的楠姐
    2020-12-13 11:02

    You might want to let your controller handle the problem by adding a method that handles this specific exception

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public String handleHttpMessageNotReadableException(HttpMessageNotReadableException ex)
    {
        JsonMappingException jme = (JsonMappingException) ex.getCause();
        return jme.getPath().get(0).getFieldName() + " invalid";
    }
    

    Of course, the line

        JsonMappingException jme = (JsonMappingException) ex.getCause();
    

    might throw a class cast exception for some cases but i haven't encountered them yet.

提交回复
热议问题