I’m writing a library that wraps around a REST API. The wrapper I’m creating uses GSON to deserialize the json into my object. Basically, something like this…
public Post getPost(url) throws IOException {
String jsonString = httpClient.get(url);
Post p = gson.fromJson(jsonString, Post.class);
// return Post to client and let client do something with it.
}
If I understand correctly, IOException is a checked exception. I’m telling my client: Hey, buddy – you better watch out and recover from this exception. Now my client can wrap the call in a try/catch and determine what to do if there is some network failure.
The GSON fromJson() method throws a JsonSyntaxException. I believe this is unchecked in the Java world, as one of its super classes is RuntimeException, and also because I am not required to add a try/catch or another “throws” like IOException.
Assuming what I have said so far is correct – how exactly should the API and client handle this situation? If the json string is garbage, my client is going to fail miserably due to the JsonSyntaxException because it’s unchecked.
// Client
PostService postService = new PostService();
try{
Post p = postService.getPost(urlString);
// do something with post
}catch (IOException){
// handle exception
}
// ok, what about a JsonSyntaxException????
What’s the best way to handle these situations?
You are allowed to catch unchecked exceptions. Just add
catch(JsonSyntaxException e)to your try-catch block. After you catch theJsonSyntaxException, you can either handle it or rethrow it as a checked exception.Ex: