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.
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 
    }
});
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