From 7e9e3ba16806e024662b0026d7713d336a3cfd88 Mon Sep 17 00:00:00 2001 From: Ross Goldberg <484615+rgoldberg@users.noreply.github.com> Date: Mon, 16 Sep 2024 01:12:23 -0400 Subject: [PATCH] Output to stderr responses from Apple endpoints that are unparsable as JSON Resolves #536 Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com> --- Sources/MasKit/Controllers/MasStoreSearch.swift | 2 +- Sources/MasKit/Errors/MASError.swift | 14 +++++++++++--- Tests/MasKitTests/Errors/MASErrorTestCase.swift | 4 ++-- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/Sources/MasKit/Controllers/MasStoreSearch.swift b/Sources/MasKit/Controllers/MasStoreSearch.swift index 43b96c651..0db3268d8 100644 --- a/Sources/MasKit/Controllers/MasStoreSearch.swift +++ b/Sources/MasKit/Controllers/MasStoreSearch.swift @@ -108,7 +108,7 @@ class MasStoreSearch: StoreSearch { do { return try JSONDecoder().decode(SearchResultList.self, from: data).results } catch { - throw MASError.jsonParsing(error: error as NSError) + throw MASError.jsonParsing(data: data) } } } diff --git a/Sources/MasKit/Errors/MASError.swift b/Sources/MasKit/Errors/MASError.swift index 716f4eae1..984b73d0d 100644 --- a/Sources/MasKit/Errors/MASError.swift +++ b/Sources/MasKit/Errors/MASError.swift @@ -28,7 +28,7 @@ public enum MASError: Error, Equatable { case uninstallFailed case noData - case jsonParsing(error: NSError?) + case jsonParsing(data: Data?) } // MARK: - CustomStringConvertible @@ -93,8 +93,16 @@ extension MASError: CustomStringConvertible { case .noData: return "Service did not return data" - case .jsonParsing: - return "Unable to parse response JSON" + case .jsonParsing(let data): + if let data { + if let unparsable = String(data: data, encoding: .utf8) { + return "Unable to parse response as JSON: \n\(unparsable)" + } else { + return "Received defective response" + } + } else { + return "Received empty response" + } } } } diff --git a/Tests/MasKitTests/Errors/MASErrorTestCase.swift b/Tests/MasKitTests/Errors/MASErrorTestCase.swift index cdefffddc..e78722b4c 100644 --- a/Tests/MasKitTests/Errors/MASErrorTestCase.swift +++ b/Tests/MasKitTests/Errors/MASErrorTestCase.swift @@ -122,7 +122,7 @@ class MASErrorTestCase: XCTestCase { } func testJsonParsing() { - error = .jsonParsing(error: nil) - XCTAssertEqual(error.description, "Unable to parse response JSON") + error = .jsonParsing(data: nil) + XCTAssertEqual(error.description, "Received empty response") } }