android 处理API调用的Ktor异常

xoshrz7s  于 2023-03-16  发布在  Android
关注(0)|答案(1)|浏览(214)

我有一个用例,比如我想在一个地方处理Ktor异常,而不是每个API调用,假设我有多个API调用,在这种情况下,我不应该复制处理异常的代码...我的代码如下所示

try {
    val modelResponse = client.get(API) {
        header("Authorization", token)
    }.body<ModelCLass>()
    response(modelResponse)
} catch (cause: HttpRequestTimeoutException) { // If we have any Time out Exception
    Log.d(TAG, "ConnectTimeoutException failure: $cause")
} catch (cause: IOException) { // Network failure is handled
    Log.d(TAG, "IOException failure: $cause")
} catch (clientException: ClientRequestException) { // If we have client side issue like invalid request (Or) data miss
    val exceptionResponse = clientException.response
    if(exceptionResponse.status == HttpStatusCode.Unauthorized) {
        // un authorized
    } else {
      // Api Error
    }
} catch (cause: Exception) { // If other general exception
    Log.d(TAG, "General Exception failure: $cause")wrong")
}

在这种catch语句的情况下,如何编写一个通用函数来处理异常

lnvxswe2

lnvxswe21#

我们可以创建一个helper方法来处理ktor应用程序中的异常,参数应该是一个异常,并向客户端返回一个适当的HTTP响应。

fun handleException(exception: Exception): HttpStatusCode {
    return when (exception) {
        is HttpRequestTimeoutException -> HttpStatusCode.GatewayTimeout
        is IOException -> HttpStatusCode.InternalServerError
        is ClientRequestException -> {
            val exceptionResponse = exception.response
            if (exceptionResponse.status == HttpStatusCode.Unauthorized) {
                HttpStatusCode.Unauthorized
            } else {
                HttpStatusCode.BadRequest
            }
        }
        else -> HttpStatusCode.InternalServerError
    }
}

像这样修改代码:

try {
    val modelResponse = client.get(API) {
        header("Authorization", token)
    }.body<ModelCLass>()
    response(modelResponse)
} catch (e: Exception) {
    val status = handleException(e)
    call.respond(status)
}

相关问题