Why isn't try/catch Exceptions working for Gson.fromJson()?

Viewed 3304

I've been getting com.google.gson.JsonSyntaxException from calling Gson.fromJson(), so added a catch(Exception) logic, but the error is never getting caught and just getting thrown!

Here's what I have:

    Request request = new Request.Builder()
            .url(getOrderUrlWithId)
            .get()
            .build();
    try {
        Response response = this.okHttpClient.newCall(request).execute();

        GetOrderResult orderResult = gson.fromJson(gson.toJson(response.body().string()), GetOrderResult.class);
        response.close();
    } catch (IOException e) {
        log.error("Error retrieving order : " + e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (Exception e) {
        log.error("Error happening for client PO: " + clientPO, e);
        return null;
    }

When I run the test I get "com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $ "

Why isn't the error getting caught?

Here's the Stack trace:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:927)
at com.google.gson.Gson.fromJson(Gson.java:892)
at com.google.gson.Gson.fromJson(Gson.java:841)
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.hub.fulfill.circlegraphics.getOrdersByCgOrderId(CircleGraphicsApi.java:164)
3 Answers

You need to catch JsonSyntaxException like this

For Kotlin

catch(e: JsonSyntaxException){

 //show toast/snackabar/log here

}

For Java

catch(JsonSyntaxException e){

 //show toast/snackabar/log here

}

Earlier I was also catching java.lang.IllegalStateException but it didn't worked. Seems the root exception here is JsonSyntaxException and thus, we need to catch this one. It worked for me!

when(...).thenReturn(null) points that you use some mocking library (jMock, Mockery or simular). And you define that if fromJson("test", Fulfillment.class) is called mock should return null. Actual method fromJson is not invoked as you already defined result. If you want expection to be thrown, then remove line

when(gson.fromJson("test", Fulfillment.class)).thenReturn(null);

Figured it out. So turns out @Slf4j's log.error() call shows the exception as an error in Google StackDriver, hence telling me I've been getting millions of errors.

Related