Swift JSON decode with readable error messages
Swift
import Foundation
func jsonPath(_ codingPath: [CodingKey]) -> String {
codingPath.isEmpty ? "root" : codingPath.map(\.stringValue).joined(separator: ".")
}
func decodeJSON<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
do {
return try JSONDecoder().decode(type, from: data)
} catch let DecodingError.keyNotFound(key, context) {
throw JSONError.message("missing key '\(key.stringValue)' at \(jsonPath(context.codingPath))")
} catch let DecodingError.typeMismatch(_, context) {
throw JSONError.message("wrong type at \(jsonPath(context.codingPath))")
} catch let DecodingError.dataCorrupted(context) {
throw JSONError.message("invalid JSON at \(jsonPath(context.codingPath))")
}
}
enum JSONError: Error { case message(String) }