[swift-evolution] [Proposal idea] Improved interop for ErrorType->NSError
Brent Royal-Gordon
brent at architechies.com
Sun Dec 20 03:14:17 CST 2015
> Whatever the solution is, it shouldn’t be invisible to developers. We need a good way to get non-NSError ErrorTypes to turn into NSErrors that have decently propagated userInfo dictionaries, so that they can be presented to the user in a form that isn’t just a cryptic “<domain> error <code>”.
No, my point is that the developer should not have to do anything special to get this bridging, or explicitly create an _NSSwiftError—it should happen automatically. Swift should take care of preserving your associated values through casts to NSError and back, and fetching your userInfo as needed; all you should need to do is tell it how to express your error's userInfo.
Actually, now that I try it, it looks like Swift *does* do this much...
1> import Foundation
2> enum MyError: ErrorType { case FileNotFound (url: NSURL) }
3> let url = NSURL(string: "missing.txt")!
url: NSURL = "missing.txt"
4> MyError.FileNotFound(url: url)
$R0: MyError = FileNotFound {
FileNotFound = {
url = "missing.txt"
}
}
5> MyError.FileNotFound(url: url) as! NSError
$R1: NSError = domain: "MyError" - code: 0 {
ObjectiveC.NSObject = {
NSObject = {
isa = _SwiftNativeNSError
}
_reserved =
_code = 0
_domain = "MyError"
_userInfo = nil
}
}
6> (MyError.FileNotFound(url: url) as! NSError) as! ErrorType
$R2: MyError = FileNotFound {
FileNotFound = {
url = "missing.txt"
}
}
7> (MyError.FileNotFound(url: url) as! NSError) as! ErrorType as! MyError
$R3: MyError = FileNotFound {
FileNotFound = {
url = "missing.txt"
}
}
Funny, I'm sure that didn't work last time I tried it...
Anyway, my point remains: this _SwiftNativeNSError should use a userInfo property on your ErrorType to populate NSError.userInfo. There should be no need to go through the full rigamarole of calling NSError's initializer yourself—just return a dictionary at the appropriate moment.
--
Brent Royal-Gordon
Architechies
More information about the swift-evolution
mailing list