Reputation: 9586
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
Reputation: 1591
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.
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
}
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