I have a custom error type in my Swift project:
struct RuntimeError : LocalizedError {
let localizedDescription: String
init(_ str : String) {
localizedDescription = str
}
}
If it is raised at the top level, I get a message like this which is useful but not quite what I expected:
Fatal error: Error raised at top level: MyApp.RuntimeError(localizedDescription: "Error message…")
If I catch it and log its .localizedDescription
, I don't even get a debug-like struct description but ± generic text instead!
E.g. the code
do {
throw RuntimeError("Message")
} catch {
NSLog("Caught error: %@", error.localizedDescription)
}
outputs only:
Caught error: The operation couldn’t be completed. (MyApp.RuntimeError error 1.)
If I change my log to (error as! RuntimeError).localizedDescription
I get the expected string, but that's not a solution since in practice not all errors will be of this type.
Why isn't my struct's localizedDescription
property used when accessed through the Error
protocol? How can I create a custom Error
or LocalizedError
struct that always provides a custom message?