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)
By default, GSON excludes transient and static fields from the serialization/deserialization process.
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.
As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With