java—当响应不成功时,如何读取改装中的错误体?

vawmfj5a  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(342)

我在android中使用改型来执行api。
示例代码段

Call<UniversalPojo> call = apiInterface.storeData(AppClass.getInstance().getLoggedInUser().getRemember_token(), requestBody);
            call.enqueue(new Callback<UniversalPojo>() {
                @Override
                public void onResponse(Call<UniversalPojo> call, Response<UniversalPojo> response) {

                    if (response.isSuccessful()) {

                    } else {

                       //I want to read code at this stage in string.

                    }
                }

                @Override
                public void onFailure(Call<UniversalPojo> call, Throwable t) {

                    t.printStackTrace();

                }
            });

我这里的问题是如何获得if(response.issusccessful())的else块的字符串错误。

rqmkfv5c

rqmkfv5c1#

使用 OkHttpClient 班级 addInterceptor(interceptor: Interceptor) 功能
覆盖 intercept(chain: Interceptor.Chain) 函数并按预期引发异常:

class NetInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val code = response.code
        val body = response.body
        // if body is null or something unexpected
        throw IOException("receive empty body")
        // else do nothing
    }
}

相关问题