Last active
January 5, 2023 09:40
-
-
Save arashkashi/af940c3d4d23f2db8d4c042cbfe33c1b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum JSONDecodingError: Error { | |
case decodingError(DecodingError) | |
case unknown | |
} | |
extension DecodingError { | |
var stringValue: String { | |
switch self { | |
case .valueNotFound(let value, let context): | |
return "Value '\(value)' not found:" + context.debugDescription + "codingPath:" + context.codingPath.map { $0.stringValue }.joined(by: "<->") | |
case .typeMismatch(let value, let context): | |
return "Value '\(value)' not found:" + context.debugDescription + "codingPath:" + context.codingPath.map { $0.stringValue }.joined(by: "<->") | |
case .dataCorrupted(let context): | |
return context.debugDescription | |
case .keyNotFound(let key, let context): | |
return "Key '\(key)' not found:" + context.debugDescription + "codingPath:" + context.codingPath.map { $0.stringValue }.joined(by: "<->") | |
@unknown default: | |
return "unknown" | |
} | |
} | |
} | |
func decode<T: Codable>(data: Data) -> Result<T, JSONDecodingError> { | |
do { | |
let decoded = try JSONDecoder() | |
.decode(T.self, | |
from: data) | |
return .success(decoded) | |
} catch let DecodingError.dataCorrupted(context) { | |
print(context) | |
return .failure(.decodingError(DecodingError.dataCorrupted(context))) | |
} catch let DecodingError.keyNotFound(key, context) { | |
print(DecodingError.keyNotFound(key, context).stringValue) | |
return .failure(.decodingError(DecodingError.keyNotFound(key, context))) | |
} catch let DecodingError.valueNotFound(value, context) { | |
print(DecodingError.valueNotFound(value, context).stringValue) | |
return .failure(.decodingError(DecodingError.valueNotFound(value, context))) | |
} catch let DecodingError.typeMismatch(type, context) { | |
print(DecodingError.typeMismatch(type, context) .stringValue) | |
return .failure(.decodingError(DecodingError.typeMismatch(type, context))) | |
} catch { | |
print("error: ", error) | |
return .failure(.unknown) | |
} | |
} | |
extension Data { | |
func decodeJSON<T: Codable>(type: T.Type) -> Result<T, JSONDecodingError> { | |
return decode(data: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment