关于android:处理Kotlin Coroutines中的自定义okhttp拦截器引发的异常

Handle exceptions thrown by a custom okhttp Interceptor in Kotlin Coroutines

我在Android应用程序中将自定义Interceptor与Retrofit客户端一起使用,在某些特定情况下会引发Exception。 我正在尝试使用Kotlin协程使其工作。

问题是我无法处理前面提到的错误,因为从Interceptor实例中引发异常的那一刻起,它使整个应用程序崩溃,而不是被协程的try/catch语句捕获。 当我使用Rx实现时,异常被完美地传播到了onError回调中,在这里我可以按照需要的方式处理它。

我猜想这与网络调用所使用的基础线程有某种关系,请在引发异常之前从进行调用的位置,拦截器以及堆栈跟踪中查看以下日志:

1
2
3
4
5
6
7
2019-11-04 17:17:34.515 29549-29729/com.app W/TAG: Running thread: DefaultDispatcher-worker-1
2019-11-04 17:17:45.911 29549-29834/com.app W/TAG: Interceptor thread: OkHttp https://some.endpoint.com/...

2019-11-04 17:17:45.917 29549-29834/com.app E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
    Process: com.app, PID: 29549
    com.app.IllegalStateException: Passed refresh token can\'t be used for refreshing the token.
        at com.app.net.AuthInterceptor.intercept(AuthInterceptor.kt:33)

为了能够正确地从拦截器捕获并处理此异常,我应该怎么做? 我想念什么吗?


您应该子类化IOException,并使用该子类将信息从拦截器发送到调用代码。

我们认为像IllegalStateException这样的其他异常是应用程序崩溃,不要将其发送到线程边界外,因为我们不想让大多数调用者都无法捕获它们。


我不知道您到底需要什么,但是这样理解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    OkHttpClient okHttpClient = new OkHttpClient.Builder()  
        .addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                okhttp3.Response response = chain.proceed(request);

                // todo deal with the issues the way you need to
                if (response.code() == SomeCode) {
                   //do something
                    return response;
                }

                return response;
            }
        })
        .build();

Retrofit.Builder builder = new Retrofit.Builder()  
        .baseUrl(url)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create());

Retrofit retrofit = builder.build();