forked from mattpolzin/JSONAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericJSONAPIError.swift
More file actions
74 lines (65 loc) · 1.91 KB
/
GenericJSONAPIError.swift
File metadata and controls
74 lines (65 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
// GenericJSONAPIError.swift
// JSONAPI
//
// Created by Mathew Polzin on 9/29/19.
//
/// `GenericJSONAPIError` can be used to specify whatever error
/// payload you expect to need to parse in responses and handle any
/// other payload structure as `.unknownError`.
public enum GenericJSONAPIError<ErrorPayload: Codable & Equatable>: JSONAPIError, CustomStringConvertible {
case unknownError
case error(ErrorPayload)
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = .error(try container.decode(ErrorPayload.self))
} catch {
self = .unknown
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .error(let payload):
try container.encode(payload)
case .unknownError:
try container.encode("unknown")
}
}
public static var unknown: Self {
return .unknownError
}
public var description: String {
switch self {
case .unknownError:
return "unknown error"
case .error(let payload):
return String(describing: payload)
}
}
}
public extension GenericJSONAPIError {
var payload: ErrorPayload? {
switch self {
case .unknownError:
return nil
case .error(let payload):
return payload
}
}
}
public protocol ErrorDictType {
var definedFields: [String: String] { get }
}
extension GenericJSONAPIError: ErrorDictType where ErrorPayload: ErrorDictType {
/// Get a dictionary of all defined fields and their values.
public var definedFields: [String: String] {
switch self {
case .unknownError:
return [:]
case .error(let basicPayload):
return basicPayload.definedFields
}
}
}