Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 604
P_equals_NP_2021 Avatar asked Dec 17 '18 22:12

P_equals_NP_2021


People also ask

Does GSON ignore transient fields?

By default, GSON excludes transient and static fields from the serialization/deserialization process.

Is GSON toJson thread safe?

Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

Does GSON ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.


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!

like image 71
Damanpreet Singh Avatar answered Oct 01 '22 00:10

Damanpreet Singh


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);
like image 40
Арсен Мирзаян Avatar answered Sep 30 '22 23:09

Арсен Мирзаян


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.

like image 27
P_equals_NP_2021 Avatar answered Oct 01 '22 00:10

P_equals_NP_2021