BadmintonCat
BadmintonCat

Reputation: 9586

Get error description from caught error

I do something like this:

let decoder = JSONDecoder()
do
{
    let decodedData = try decoder.decode(type, from: data)
}
catch DecodingError.dataCorrupted
{
    let descr = ???
    Log.error("Failed to decode JSON response. Error was: \(descr)")
}

how can I access the error description from this? Why can I not simply catch any kind of error in one catch and access its debug description?

Upvotes: 0

Views: 499

Answers (1)

Julien Perrenoud
Julien Perrenoud

Reputation: 1591

How to access the error description

In Swift, a lot of the errors conform to the protocol LocalizedError, which will give you a variable localizedDescription: String? that you can use to print an error message. DecodingError should not be any different.

How to catch any kind of error

You should be able to catch any kind of errors in one catch. In order to do this, you can use

catch let error as DecodingError {
    // Any error of type DecodingError
}

or

catch {
    // Any possible error
}

Putting it all together

If I understand correctly, you are tring to catch any error of type DecodingError. In that case, you can simply do the following

let decoder = JSONDecoder()
do {
    let decodedData = try decoder.decode(type, from: data)
} catch let error as? DecodingError {
    Log.error("Failed to decode JSON response. Error was: \(String(describing: error.localizedDescription))")
}

Upvotes: 1

Related Questions