简体   繁体   中英

How to throw a custom exception from a custom deserializer

I have a class deserialized by my custom deserializer and I need to throw my custom exception.

public class MyClass {
}

public static void main(String[] args) {
    try {
        ObjectMapper mapper = new ObjectMapped();
        MyClass myClass = mapper.readValue(json, MyClass.class);
    } catch(Exception e) {
        System.out.println(e);                // JsonMappingException
        System.out.println(e.getCause());     // null, but I need to get my CustomException.class
    }
}

public class MyDeserializer extends StdDeserializer<MyClass> {
    @Override
    public MyClass deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        throw new CustomException("TestException", 1);
    }
}

public class CustomException extends IOException {
    private int code;
    
    public CustomException(String message, int code) {
        super(message);
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

What can I do to return my custom exception from the custom deserializer?

First you should add custom desializer to ObjectMapper or target Object like below

@JsonDeserialize(using = MyDeserializer.class)
public class MyClass {

}

getCause() return null because you already have caused Exception, check getCause implementation

  public synchronized Throwable getCause() {
        return (cause==this ? null : cause);
    }

shorty you don't need to getCause, e is your CustomException instance. Just do first step and remove getCause, it ll be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM