Kamilski81
Kamilski81

Reputation: 15117

How do I prevent Java RetroFit from crashing my app on a 401 Unauthorized error?

My app crashes whenever a 401 error occurs in the app. I created a custom error handler but i'm not sure how to get the app to use this error handler so the app stops gracefully, without flashing the user "Unforunately, Application has stopped."

Here's my code:

    ... new RestAdapter.Builder()...setErrorHandler(getErrorHandler()).build();



    public ErrorHandler getErrorHandler() {
        return new ErrorHandler() {
            @Override
            public Throwable handleError(RetrofitError cause) {
                Response r = cause.getResponse();
                if (r != null && r.getStatus() == 401) {
                    Log.e(TAG, "user not authorized:" + cause.toString());
                } else {
                    Log.e(TAG, "regular exception thrown for CloudManager");
                }

                return cause;
            }
        };

Upvotes: 2

Views: 1409

Answers (1)

Sergii Pechenizkyi
Sergii Pechenizkyi

Reputation: 22232

As you can check with javadoc ErrorHandler is used when you want to wrap RetrofitError into CustomError exception. It doesn't catch exception for you.

class MyErrorHandler implements ErrorHandler {
   @Override public Throwable handleError(RetrofitError cause) {
     Response r = cause.getResponse();
     if (r != null && r.getStatus() == 401) {
       return new UnauthorizedException(cause);
     }
     return cause;
   }
 }

To prevent app from crashing you have to catch error earlier.

@GET("/users/{user}/repos")
List<Repo> listRepos(@Path("user") String user);

try {
    List<Repo> repos = retrofit.listRepos("octocat");
} catch (RetrofitError error) {
    // TODO: handle error
}

Upvotes: 4

Related Questions