Samzerge
Samzerge

Reputation: 106

How to handle errors from onFailure method in Retrofit?

When making a http-request with Retrofit sometimes the onFailure method (from the Callback interface) is called instead of the onResponse. The problem is that the Throwable returned in this method comes with null fields. Meaning, the getMessage(), getLocalizedMessage() and the getCause() methods, all return null.

Is there a known reason of why the onFailure() is called like this? Is there another way of knowing why the onFailure() method was called?

Upvotes: 3

Views: 2080

Answers (1)

iagreen
iagreen

Reputation: 32026

When executing the call, retrofit executes third party code in the form of adapters and converters. Because of that, it is hard to predict all the various exceptions it might encounter. When onFailure is called, something threw an exception - either retrofit, okhttp, or an adapter or converter. You can handle it much like you would a thrown exception except you don't need to catch it. When you are debugging, use t.printStackTrace() to get a handle on what went wrong and if it is preventable. You can also look for specific exceptions by checking the type of the exception. For example, IOException is common because of network failures --

if (t instanceof IOException) {
    // Handle IO exception, maybe check the network and try again.
} 

Upvotes: 2

Related Questions