From 8eb241ccce345a35b05a6335d11306465220f66d Mon Sep 17 00:00:00 2001 From: Torsten Grote Date: Thu, 23 Jul 2020 15:41:50 -0300 Subject: [pos] refactor configuration fetching and validation --- .../src/main/java/net/taler/merchantlib/Response.kt | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) (limited to 'merchant-lib/src/main/java/net/taler/merchantlib/Response.kt') diff --git a/merchant-lib/src/main/java/net/taler/merchantlib/Response.kt b/merchant-lib/src/main/java/net/taler/merchantlib/Response.kt index eb1ef27..1b49d78 100644 --- a/merchant-lib/src/main/java/net/taler/merchantlib/Response.kt +++ b/merchant-lib/src/main/java/net/taler/merchantlib/Response.kt @@ -50,14 +50,29 @@ class Response private constructor( } } + suspend fun handleSuspend( + onFailure: ((String) -> Any)? = null, + onSuccess: (suspend (T) -> Any)? = null + ) { + if (value is Failure) onFailure?.let { it(getFailureString(value)) } + else onSuccess?.let { + @Suppress("UNCHECKED_CAST") + it(value as T) + } + } + private suspend fun getFailureString(failure: Failure): String = when (failure.exception) { is ClientRequestException -> getExceptionString(failure.exception) else -> failure.exception.toString() } private suspend fun getExceptionString(e: ClientRequestException): String { - val error: Error = e.response.receive() - return "Error ${error.code}: ${error.hint}" + return try { + val error: Error = e.response.receive() + "Error ${error.code}: ${error.hint}" + } catch (ex: Exception) { + "Status code: ${e.response.status.value}" + } } private class Failure(val exception: Throwable) -- cgit v1.2.3