-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDecodingErrorFormatter.swift
87 lines (66 loc) · 2.7 KB
/
DecodingErrorFormatter.swift
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
75
76
77
78
79
80
81
82
83
84
85
86
87
import Foundation
extension String {
fileprivate func repeatFor(_ times: Int) -> String {
var newString = self
for _ in 1..<times {
newString += self
}
return newString
}
}
extension DecodingError {
public func debug() {
print(divider)
switch self {
case .keyNotFound(let codingKey, let context): handleKeyNotFound(codingKey: codingKey, context: context)
case .typeMismatch(_, let context): handleTypeMismatch(context: context)
case .valueNotFound(_, let context): handleValueNotFound(context: context)
case .dataCorrupted(let context): handleDataCorrupted(context: context)
default: defaultHandler()
}
print(divider)
}
// MARK: - PRIVATES
// MARK: Properties
private var prefix: String {
return "|||"
}
private var divider: String {
return "\(prefix) ------------------"
}
// MARK: Methods
private func handleKeyNotFound(codingKey: CodingKey, context: Context) {
print("\(prefix) DECODING ERROR: KEY NOT FOUND IN HIERARCHY")
for (index, codingPath) in context.codingPath.enumerated() {
print("\(prefix) \("-".repeatFor(index + 1))> \(codingPath.stringValue)")
}
print("\(prefix) \("-".repeatFor(context.codingPath.count + 1))> \(codingKey.stringValue)")
}
private func handleTypeMismatch(context: Context) {
print("\(prefix) DECODING ERROR: TYPE MISMATCH IN HIERARCHY")
for (index, codingPath) in context.codingPath.enumerated() {
print("\(prefix) \("-".repeatFor(index + 1))> \(codingPath.stringValue)")
}
print("\(prefix) \("-".repeatFor(context.codingPath.count + 1))> \(context.debugDescription)")
}
private func handleValueNotFound(context: Context) {
print("\(prefix) DECODING ERROR: VALUE NOT FOUND IN HIERARCHY")
for (index, codingPath) in context.codingPath.enumerated() {
print("\(prefix) \("-".repeatFor(index + 1))> \(codingPath.stringValue)")
}
print("\(prefix) \("-".repeatFor(context.codingPath.count + 1))> \(context.debugDescription)")
}
private func handleDataCorrupted(context: Context) {
print("\(prefix) DECODING ERROR: DATA CORRUPTED")
print("\(prefix) -> \(context.debugDescription)")
guard let error = context.underlyingError else { return }
print("\(prefix) -> \(error.localizedDescription)")
if let errorMessage = (error as NSError).userInfo[NSDebugDescriptionErrorKey] {
print("\(prefix) -> \(errorMessage)")
}
}
private func defaultHandler() {
print("\(prefix) DECODING ERROR")
print(self)
}
}