StuartDTO
StuartDTO

Reputation: 1031

MockWebServer not throwing custom exception retrofit

I'm implementing mockWebServer and it works for the 200 calls, but when I try to get an exception I'm getting this exception :

Exception in thread "OkHttp Dispatcher" java.lang.Error: com.myproject.something.errors.MyException$ServerUnavailable at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1155) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748)

And this one

Caused by: com.myproject.something.errors.ServerException$ServiceUnavailable at com.myproject.something.errors.MyException$ServerUnavailable.(ServerException.kt:6) at com.myproject.ErrorInterceptor.intercept(IntegrationTest.kt:86)

I have this error interceptor for the fake retrofit

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)
        }
}

And I'm enqueueing the call correctly, I'm just sending a 503 as a response...

This is my test

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

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

What do I miss there?

Upvotes: 0

Views: 1478

Answers (1)

Jesse Wilson
Jesse Wilson

Reputation: 40593

Change your custom exception to extend IOException. OkHttp interceptors that throw exceptions other than IOException are delivered to the uncaught exception handler.

Upvotes: 1

Related Questions