【问题标题】:MockWebServer not throwing custom exception retrofitMockWebServer 不抛出自定义异常改造
【发布时间】:2020-08-12 23:27:53
【问题描述】:

我正在实现 mockWebServer,它适用于 200 次调用,但是当我尝试获取异常时,我得到了这个异常:

线程“OkHttp Dispatcher”中的异常 java.lang.Error: com.myproject.something.errors.MyException$ServerUnavailable 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1155) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) 在 java.lang.Thread.run(Thread.java:748)

还有这个

原因:com.myproject.something.errors.ServerException$ServiceUnavailable 在 com.myproject.something.errors.MyException$ServerUnavailable.(ServerException.kt:6) 在 com.myproject.ErrorInterceptor.intercept(IntegrationTest.kt:86)

我有这个假改造的错误拦截器

class ErrorInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response =
        try {
            val response = chain.proceed(chain.request())
            if (!response.isSuccessful) {
                when (response.code) {
                    HttpURLConnection.HTTP_UNAVAILABLE -> throw MyException.ServiceUnavailable
                    else -> throw ServerException(IllegalStateException("Not handled"))
                }
            }
            response
        } catch (error: IOException) {
            throw ServiceException(error)
        }
}

我正在正确地排队呼叫,我只是发送一个 503 作为响应......

这是我的测试

 @Test(expected = MyException.ServerUnavailable::class)
    fun test2() {

        mock Response with HttpURLConnection.HTTP_UNAVAILABLE
        runBlocking {
            apiService.doThecall()
        }
    }

我错过了什么?

【问题讨论】:

    标签: android kotlin retrofit okhttp mockwebserver


    【解决方案1】:

    更改您的自定义异常以扩展 IOException。抛出除 IOException 以外的异常的 OkHttp 拦截器被传递给未捕获的异常处理程序。

    【讨论】:

    • 知道为什么我得到的是 ServiceException 而不是 MyException.ServiceUnavailable 吗?直接去catch,不用找响应码
    猜你喜欢
    • 2011-10-06
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多