如何处理okhttp3中的错误而不会崩溃

问题描述 投票:1回答:2

我正在使用以下方法来处理我的请求

override fun intercept(chain: Interceptor.Chain): Response = chain.proceed(chain.request())
        .let { originalResponse ->

            Log.i("AMIRA999", "code : " + originalResponse.code())

            when (originalResponse.code()) {

                200 -> {
                    Log.i("AMIRA999", "body : " + getErrorResponse(originalResponse))
                    originalResponse
                }
                401, 404 -> {


                    Log.i("AMIRA999", "body : " + getErrorResponse(originalResponse))
                    originalResponse

                    /*return originalResponse.mapToBody(
                        originalResponse.body()?.contentType(),
                        getErrorResponse(originalResponse)
                    )*/
                }
                else -> {
                    Log.i("AMIRA999", "body : " + originalResponse.body().toString())
                    throw BadRequestException()
                }
            }
        }

该方法在代码为200时工作完美,但是如果代码为404或401,则会崩溃

我需要继续返回的json来自服务器,并且不会崩溃以能够通过错误消息进行处理

我该怎么做?

我得到的崩溃是以下

retrofit2.HttpException: HTTP 401 UNAUTHORIZED
at com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory$BodyCallAdapter$adapt$2.onResponse(CoroutineCallAdapterFactory.kt:104)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:129)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:206)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
android kotlin retrofit2 okhttp
2个回答
1
投票
if (response.isSuccessful) { deferred.complete(response.body()!!) } else { deferred.completeExceptionally(HttpException(response)) }

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.