From 1ed24fcda3fb3e00dc8d037cc2c0fabde5e216f9 Mon Sep 17 00:00:00 2001 From: Benedikt Terhechte Date: Tue, 19 Apr 2022 14:50:53 +0200 Subject: [PATCH] Improved Error forwarding --- Sources/SwiftGraphQL/HTTP.swift | 21 ++++++++++++++++----- Sources/SwiftGraphQL/Result.swift | 6 +++--- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/Sources/SwiftGraphQL/HTTP.swift b/Sources/SwiftGraphQL/HTTP.swift index c216fb81..0af123c7 100644 --- a/Sources/SwiftGraphQL/HTTP.swift +++ b/Sources/SwiftGraphQL/HTTP.swift @@ -113,8 +113,15 @@ private func send( } // Try to serialize the response. - if let data = data, let result = try? GraphQLResult(data, with: selection) { - return completionHandler(.success(result)) + if let data = data { + do { + let result = try GraphQLResult(data, with: selection) + return completionHandler(.success(result)) + } catch let error as HttpError { + return completionHandler(.failure(error)) + } catch let error { + return completionHandler(.failure(.decodingError(error))) + } } return completionHandler(.failure(.badpayload)) @@ -139,6 +146,7 @@ public enum HttpError: Error { case badpayload case badstatus case cancelled + case decodingError(Error) } extension HttpError: Equatable { @@ -146,9 +154,12 @@ extension HttpError: Equatable { // Equals if they are of the same type, different otherwise. switch (lhs, rhs) { case (.badURL, badURL), - (.timeout, .timeout), - (.badpayload, .badpayload), - (.badstatus, .badstatus): + (.timeout, .timeout), + (.badpayload, .badpayload), + (.badstatus, .badstatus), + (.cancelled, .cancelled), + (.network, network), + (.decodingError, decodingError): return true default: return false diff --git a/Sources/SwiftGraphQL/Result.swift b/Sources/SwiftGraphQL/Result.swift index 83e77399..a7f86025 100644 --- a/Sources/SwiftGraphQL/Result.swift +++ b/Sources/SwiftGraphQL/Result.swift @@ -17,9 +17,9 @@ extension GraphQLResult where TypeLock: Decodable { let response = try decoder.decode(GraphQLResponse.self, from: response) self.data = try selection.decode(data: response.data) self.errors = response.errors - } catch { + } catch let error { // Catches all errors and turns them into a bad payload SwiftGraphQL error. - throw HttpError.badpayload + throw HttpError.decodingError(error) } } @@ -46,7 +46,7 @@ extension GraphQLResult where TypeLock: Decodable { // MARK: - GraphQL Error public struct GraphQLError: Codable, Equatable { - let message: String + public let message: String public let locations: [Location]? // public let path: [String]?