From 384098d064d6543e835d5f811caf02e9a151018f Mon Sep 17 00:00:00 2001 From: Marek Stransky <77441794+Hopsaheysa@users.noreply.github.com> Date: Fri, 27 Oct 2023 10:24:12 +0200 Subject: [PATCH] Separated code to more do-catch blocks to have more log possibilities (#40) * Separate code to more do-catch blocks to have more log possibilities * Implement the suggested improvements * Empty commit --- .../WPNHttpRequest.swift | 42 +++++++++++++++---- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/Sources/WultraPowerauthNetworking/WPNHttpRequest.swift b/Sources/WultraPowerauthNetworking/WPNHttpRequest.swift index 23af7a5..2bfd3f4 100644 --- a/Sources/WultraPowerauthNetworking/WPNHttpRequest.swift +++ b/Sources/WultraPowerauthNetworking/WPNHttpRequest.swift @@ -136,11 +136,18 @@ class WPNHttpRequest { /// Parses given result data and sets it to `response` property func processResult(data: Data) -> ProcessResultResponse { - - do { - if let encryptor = encryptor { + + if let encryptor = encryptor { + do { if let decryptedData = encryptor.decryptResponse(try jsonDecoder.decode(E2EEResponse.self, from: data).toCryptorgram()) { - return .encrypted(obj: try jsonDecoder.decode(TResponse.self, from: decryptedData), decryptedData: decryptedData) + do { + let decryptedResponse = try jsonDecoder.decode(TResponse.self, from: decryptedData) + return .encrypted(obj: decryptedResponse, decryptedData: decryptedData) + } catch { + D.error("failed to decode decrypted response:\n\(error)") + D.error("from decryptedData: \(decryptedData.forLog())") + return .failed(error: error) + } } else { D.error("failed to decrypt response") @@ -152,12 +159,19 @@ class WPNHttpRequest { return .failed(error: WPNSimpleError(message: "failed to decrypt response")) } - } else { + } catch { + D.error("failed to decrypt response:\n\(error)") + D.error("from data: \(data.forLog())") + return .failed(error: error) + } + } else { + do { return .plain(obj: try jsonDecoder.decode(TResponse.self, from: data)) + } catch { + D.error("failed to decode the response:\n\(error)") + D.error("from data: \(data.forLog())") + return .failed(error: error) } - } catch { - D.error("failed to process result:\n\(error)") - return .failed(error: error) } } } @@ -193,3 +207,15 @@ private struct E2EEResponse: Decodable { return cryptogram } } + +private extension Data { + func forLog() -> String { + // If the Data instance can’t be converted to a UTF-8 string, you’ll get back an empty string. + let decoded = String(decoding: self, as: UTF8.self) + if decoded.isEmpty == false { + return decoded + } else { + return "Data could not be stringified. Here is a base64 encoded version of it: \(self.base64EncodedString())" + } + } +}