How to notify one listener of every failed Httprequest using Retrofit on Android

I use Retrofit to connect my application to webbackend. We use asynchronous callback methods to execute queries at different points in the application.

How to add a listener that will be notified every time an http request fails.

My current idea is to create a custom callback class that should extend to all callbacks in my application. This callback will inform my listener of every failure.

If I change the entire Interface except for the subtypes of this class and make a final failure and success method — with an abstract method callback — it should not be possible to miss the call in the entire application.

Is there an easier way than this?

+3
source share
1 answer

An easy approach for this is to use a callback, but you can also send an event to your activity using any event infrastructure or using a local broadcast of events, for example:

  • to send an event, you should use something like:

        private void sendMessage() {
          Intent intent = new Intent("event-networkerror");
          intent.putExtra("message", "data");
          LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }  
    
  • To sign up for an event:

        public void onResume() {
          super.onResume();
          // Register mMessageReceiver to receive messages.
          LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
              new IntentFilter("event-networkerror"));
        }
    
        // handler for received Intents for the "my-event" event 
        private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
          public void onReceive(Context context, Intent intent) {
            // Extract data included in the Intent
            String message = intent.getStringExtra("message");
            Log.d("receiver", "Got message: " + message);
          }
        };
    
        protected void onPause() {
          // Unregister since the activity is not visible
          LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
          super.onPause();
        } 
    

You can use ErrorHandler to send a broadcast:

        class MyErrorHandler implements ErrorHandler {
          public Throwable handleError(RetrofitError cause) {
            Response r = cause.getResponse();
            // process error r.getStatus()
            Intent intent = new Intent("event-networkerror");
            intent.putExtra("status",r.getStatus());
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            return cause;
          }
        }

        RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint("...")
        .setErrorHandler(new MyErrorHandler())
        .build();
0
source

All Articles