Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

json - Error handling using JSONDecoder in Swift

I am using JSONDecoder() in Swift and need to get better error messages.

Within the debug description (for example) I can see messages like "The given data was not valid JSON", but I need to know it is that rather than a network error (for example).

    let decoder = JSONDecoder()
    if let data = data{
        do {
            // process data

        } catch let error {
           // can access error.localizedDescription but seemingly nothing else
    }

I tried to cast to a DecodingError, but this does not seem to reveal more information. I certainly don't need the string - even an error code is much more helpful than this...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Never print error.localizedDescription in a decoding catch block. This returns a quite meaningless generic error message. Print always the error instance. Then you get the desired information.

let decoder = JSONDecoder()
    if let data = data {
        do {
            // process data

        } catch  {
           print(error)
    }

Or for the full set of errors use

let decoder = JSONDecoder()
if let data = data {
    do {
       // process data
    } catch let DecodingError.dataCorrupted(context) {
        print(context)
    } catch let DecodingError.keyNotFound(key, context) {
        print("Key '(key)' not found:", context.debugDescription)
        print("codingPath:", context.codingPath)
    } catch let DecodingError.valueNotFound(value, context) {
        print("Value '(value)' not found:", context.debugDescription)
        print("codingPath:", context.codingPath)
    } catch let DecodingError.typeMismatch(type, context)  {
        print("Type '(type)' mismatch:", context.debugDescription)
        print("codingPath:", context.codingPath)
    } catch {
        print("error: ", error)
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...