[swift-evolution] [Discussion] Adopting a new common error type outside the bounds of NSError

Ben Rimmington me at benrimmington.com
Mon Mar 7 05:20:26 CST 2016

> On 7 Mar 2016, at 08:16, Kevin Ballard via swift-evolution <swift-evolution at swift.org> wrote:
>>>> CustomStringConvertible for Simple Error Messages
>>>> ----------------------------------------------------------------------
>>>> I think that we should encourage developers to conform errors with user-readable error messages to CustomStringConvertible and implement `description` to return that error. To that end, when a CustomStringConvertible Swift error is bridged to NSError, its `description` should become the NSError's `localizedDescription`. That ends up looking like this:
>>> I disagree here too. My CustomStringConvertible representation of my error may not be at all suitable for the localizedDescription of an NSError. The NSError's localizedDescription should be a string that is suitable for presenting to the user, but CustomStringConvertible isn't necessarily intended for showing to a user. For example, my enum's string representation may be "IOError(code: 3, path: "/tmp/foo")", which is certainly not what you want the user to see.
>> Primarily, I am suggesting that we should have *a standard protocol* for "give me a textual version of this instance that I can show to a user" and that we should, by convention, use that on `Error`s to convey error messages for errors that are suitable to present to users.
> You'd want to invent a new protocol for this purpose, then, as there's no built-in protocol that is defined such that it produces values suitable for NSError.localizedDescription. CustomStringConvertible just provides some way to produce a String from a value. It doesn't say anything about what that String is meant for. And the types of strings that you want for NSError.localizedDescription are rather unlikely to be the strings that people choose to return from CustomStringConvertible.description. localizedDescription is typically a complete grammatical sentence, whereas CustomStringConvertible usually just provides a description of the value itself

CFError and NSError also support:

> kCFErrorDescriptionKey
> Key to identify the description in the userInfo dictionary.
> When you create a CFError object, you can provide a value for this key if you do not have localizable error strings. The description should be a complete sentence if possible, and should not contain the domain name or error code.
> Available in OS X v10.5 and later.


The default localizedDescription becomes "The operation couldn’t be completed. (<domain> error <code> - <description>)".

-- Ben

More information about the swift-evolution mailing list