Jackson and this is a terrible IOException

The Jackson member ObjectMapper#readValue selected three verified exceptions:

IOException 
JsonParseException 
JsonMappingException

JsonParseExceptionand JsonMappingExceptioncontinue IOException. I want to wrap the two above child classes and throw my own custom exceptions, but the base class IOExceptionbeing checked requires that I either hook or throw it.

I have nothing to throw IOExceptionup to the calling layer, but, unfortunately, it is a smell if I hide it. My initial thought was to not catch her and leave her in the caller / time exclusion mechanism to deal with her ... but I don't want to get the caller to catch or point.

What are you doing in this situation?

+5
source share
3 answers

The short answer is: if you are dealing with IO, you are dealing with IOExceptions. If you are not dealing with IO, then you IOExceptionshould turn it into excluded exceptions, because they are signs of an erroneous code.


Longer answer:

readValuealways accepts JsonParser, which can be wrapped around I / O (such as a file or URL). If you are dealing with IO, there is no way to deal with IOExceptions, and you must either process them or transfer / transfer them somehow. Anything can happen during I / O, and you should be prepared to handle exceptions.

, , JsonParser IO (, JsonFactory#createJsonParser(java.lang.String) JSON ), , IOException, , , , . - :

ObjectMapper om = new ObjectMapper(/* whatever */);
JsonParser jp = JsonFactory.createJsonParser("{ \"foo\": \"bar\" }");
try {
    return om.readValue(jp);
} catch (IOException e) {
    throw new AssertionError("An IOException occurred when this was assumed to be impossible.");
}

Nota bene: Java , , .

AssertionError throws, . , java.lang.RuntimeException java.lang.Error . , , , , - VM .

+8

IOException , json . , , - ( " " ).

+1

Jackson, IOExceptions : IO ( ) - , . IOExceptions , ( ) -, , , UTF-8.

From this, it seems relatively intuitive that JsonParsingException is for problems associated with trying to parse inappropriate content; and JsonMappingException for data binding problems. and

0
source

All Articles