From d4167ea7f560357f97a1eb4bdc13e3d1a7d86434 Mon Sep 17 00:00:00 2001 From: darronschall Date: Wed, 15 Feb 2023 14:12:08 -0500 Subject: [PATCH] Add a helper to determine if an exception is from a `304 Not Modified` response. In practice, Ktor will throw a `RedirectResponseException` on a `304 Not Modified` server result. This small helper lets us avoid having to repeat ourselves with a cast and status check when we're trying to determine what happened in our exception handling: ```kotlin try { val (response, responseHeaders) = exampleService.getCacheData(...) } catch (e: ServiceException) { if (e.isNotModifiedException()) { // Ignore, local cache is not stale. } } ``` --- .../com/collectiveidea/twirp/ServiceException.kt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/runtime/src/commonMain/kotlin/com/collectiveidea/twirp/ServiceException.kt b/runtime/src/commonMain/kotlin/com/collectiveidea/twirp/ServiceException.kt index 1839465..0602689 100644 --- a/runtime/src/commonMain/kotlin/com/collectiveidea/twirp/ServiceException.kt +++ b/runtime/src/commonMain/kotlin/com/collectiveidea/twirp/ServiceException.kt @@ -1,6 +1,13 @@ package com.collectiveidea.twirp +import io.ktor.client.plugins.RedirectResponseException import io.ktor.client.plugins.ResponseException +import io.ktor.http.HttpStatusCode -class ServiceException(val error: ErrorResponse, responseException: ResponseException) : - RuntimeException(error.msg, responseException) +class ServiceException(val error: ErrorResponse, val responseException: ResponseException) : + RuntimeException(error.msg, responseException) { + + fun isNotModifiedException(): Boolean { + return responseException is RedirectResponseException && responseException.response.status == HttpStatusCode.NotModified + } +}