Search code examples
swifterror-handlingcodable

How I can fetch codingPath when codable issue happens?


I tried this, but it raise an error:

do {
            guard let firstValue = result.values.first else {
                completion?(nil, NSError(domain: "MyDomain", code: 1, userInfo: [NSLocalizedDescriptionKey: "No first value found"]))
                return
            }
            let jsonData = try JSONSerialization.data(withJSONObject: firstValue, options: [])
            let jsonStr = String(data: jsonData, encoding: .utf8)
            //print(jsonStr!)
            let decoder = JSONDecoder()
            let decodedObject = try decoder.decode(T.self, from: jsonData)
            completion?(decodedObject, nil)
        } catch let decodingError as DecodingError {
            print("Failed to decode JSON: \(decodingError)")
            if let context = decodingError.context { // <----- HERE
                print("Coding path: \(context.codingPath)")
            }
        } catch let error {
            print("An error occurred: \(error)")
            // handle the error here
        }

Type of expression is ambiguous without more context


Solution

  • Expanding on Joakim post if you would like to use the syntax at your post you can extend DecodingError enum as follow:

    extension DecodingError {
    
        var context: Context {
            let context: Context
            switch self {
            case let .dataCorrupted(ctxt):
                context = ctxt
            case let .keyNotFound(_, ctxt):
                context = ctxt
            case let .typeMismatch(_, ctxt):
                context = ctxt
            case let .valueNotFound(_, ctxt):
                context = ctxt
            @unknown default:
                fatalError()
            }
            return context
        }
    
        var codingPath: [CodingKey] {
           context.codingPath
        }
    
        var underlyingError: Error? {
            context.underlyingError
        }
    }