|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/// A structure that represents a custom error returned by the API |
| 4 | +/// in the request response. |
| 5 | +internal struct APIError: Error { |
| 6 | + let statusCode: Int |
| 7 | + let underlayingError: RailsError |
| 8 | + |
| 9 | + init?( |
| 10 | + response: Network.Response, |
| 11 | + decodingConfiguration: DecodingConfiguration |
| 12 | + ) { |
| 13 | + let decoder = JSONDecoder(decodingConfig: decodingConfiguration) |
| 14 | + guard |
| 15 | + let data = response.data, |
| 16 | + let decodedError = try? decoder.decode(RailsError.self, from: data) |
| 17 | + else { |
| 18 | + return nil |
| 19 | + } |
| 20 | + |
| 21 | + self.statusCode = response.statusCode |
| 22 | + self.underlayingError = decodedError |
| 23 | + } |
| 24 | + |
| 25 | + /// Returns the first error returned by the API |
| 26 | + var firstError: String? { |
| 27 | + if let errors = underlayingError.errors, let firstMessage = errors.first { |
| 28 | + return "\(firstMessage.key) \(firstMessage.value.first ?? "")" |
| 29 | + } else if let errorString = underlayingError.error { |
| 30 | + return errorString |
| 31 | + } |
| 32 | + |
| 33 | + return nil |
| 34 | + } |
| 35 | + |
| 36 | + /// Returns an array containing all error values returned from the API |
| 37 | + var errors: [String] { |
| 38 | + var flattenedErrors = underlayingError.errors? |
| 39 | + .compactMap { $0.value } |
| 40 | + .flatMap { $0 } |
| 41 | + |
| 42 | + if let errorString = underlayingError.error { |
| 43 | + flattenedErrors?.append(errorString) |
| 44 | + } |
| 45 | + |
| 46 | + return flattenedErrors ?? [] |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// A structure that represents a Ruby on Rails API error object |
| 51 | +internal struct RailsError: Decodable { |
| 52 | + |
| 53 | + let errors: [String: [String]]? |
| 54 | + let error: String? |
| 55 | + |
| 56 | + enum CodingKeys: String, CodingKey { |
| 57 | + case errors |
| 58 | + case error |
| 59 | + } |
| 60 | + |
| 61 | + init(from decoder: Decoder) throws { |
| 62 | + let values = try decoder.container(keyedBy: CodingKeys.self) |
| 63 | + if let errors = try? values.decode([String: [String]].self, forKey: .errors) { |
| 64 | + self.errors = errors |
| 65 | + self.error = nil |
| 66 | + } else if let error = try? values.decode(String.self, forKey: .errors) { |
| 67 | + self.error = error |
| 68 | + self.errors = nil |
| 69 | + } else { |
| 70 | + error = try? values.decode(String.self, forKey: .error) |
| 71 | + errors = nil |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments