How to catch the Exception in Retrofit android

后端 未结 2 2025
抹茶落季
抹茶落季 2021-01-29 02:52
  1. I have defined the classes as below.
  2. I have used dagger with Retrofit here

What I am trying to do::

I am trying to catch t

相关标签:
2条回答
  • 2021-01-29 03:20

    As I know, there is no internet connection the RetrofitError contains a ConnectionException as the cause.

    public class RetrofitErrorHandler implements ErrorHandler {
    
        @Override
        public Throwable handleError(RetrofitError cause) {
            if (cause.isNetworkError()) {
                if (cause.getCause() instanceof SocketTimeoutException) {
                      /* your code here*/ 
                    return new MyConnectionTimeoutException();
                } else {
                    /* your code here*/
                    return new MyNoConnectionException();
                }
            } else {
                //Do whatever you want to do if there is not a network error.  
            }
        }
    }
    

    Or you can create a custom Retrofit client that checks for connectivity before executing a request and throws an exception.

    public class ConnectivityCheck implements Client {
    
        Logger log = LoggerFactory.getLogger(ConnectivityCheck.class);
    
        public ConnectivityCheck (Client wrappedClient, NetworkConnectivityManager ncm) {
            this.wrappedClient = wrappedClient;
            this.ncm = ncm;
        }
    
        Client wrappedClient;
        private NetworkConnectivityManager ncm;
    
        @Override
        public Response execute(Request request) throws IOException {
            if (!ncm.isConnected()) {
                log.debug("No connectivity %s ", request);
                throw new NoConnectivityException("No connectivity");
            }
            return wrappedClient.execute(request);
        }
    }
    

    and then use it when configuring RestAdapter

    RestAdapter.Builder().setEndpoint(serverHost)
                         .setClient(new ConnectivityCheck(new OkHttpClient(), ...))
    
    0 讨论(0)
  • 2021-01-29 03:35

    As far as I know, I don't think Retrofit supports 'connectivity checking in call time' and I don't think that is exactly what you want.

    Try to check connectivity before your call, for example,

    private void sendData() {
        if( isConnected ) {
              switch(call) {
                   case "userSignIn":
                          Call !
                          break;
                   ...
        }
    }
    

    Maybe you can check this solution too

    0 讨论(0)
提交回复
热议问题