Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is error handling done in Retrofit 2 ? I can not find the RetrofitError class that most of the solutions suggest?

I want to implement a error handling mechanism using Retorfit 2.

The solutions that are available are using RetrofitError class which I can't find in the current repo.

like image 893
Khalil Avatar asked Sep 11 '15 06:09

Khalil


1 Answers

If you are making synchronous request, you define your request method in the interface as Call<List<Car>>.

Once you execute the request you receive response and deserialized data wrapped in Response<T> as Response<List<Car>>. This wrapped gives you access to headers, http codes and raw response body.

You can access error body as:

 Call<List<Car>> carsCall = carInterface.loadCars();

   try {
      Response<List<Car>> carsResponse = carsCall.execute();
        } catch (IOException e) {
           e.printStackTrace();
           //network Exception is throw here
        }
     if(carsResponse != null && !carsResponse.isSuccess() && carsReponse.errorBody() != null){
          // handle carsResponse.errorBody()
     } 

For async calls, you receive Throwable, if I/O exception is thrown during the network call:

Call<List<Car>> call = service.loadCars();
call.enqueue(new Callback<List<Car>>() {
    @Override
    public void onResponse(Response<List<Car>> response) {
        // Get result from response.body(), headers, status codes, etc
    }

    @Override
    public void onFailure(Throwable t) {
      //handle error 
    }
});
like image 88
Nikola Despotoski Avatar answered Oct 21 '22 09:10

Nikola Despotoski