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

Erica Sadun erica at ericasadun.com
Sun Mar 6 11:17:54 CST 2016


NSError encapsulates runtime error condition information. It uses an historic, time-tested object
built to communicate information to users and provide a basis for workarounds. 
Swift's redesigned error mechanism differs significantly from NSError in that its primary consumer
are API calls, via the try-catch mechanism and not end-users.

I would not like Swift to be tied down to an archaic construct for the sake of consistency. NSError's
core domain/code/userInfo attributes are architected to archaic use-cases. It domains of
Mach/POSIX/Carbon/Cocoa are subsumed by Swift modules. The integer-based codes 
can be better represented by plain-text strings, the dictionary keys model usage that 
poorly integrates into Swift's throw-try ecosystem.

To me, an error should answer the following questions:

* What went wrong?
* Where did it go wrong?
* What other information am I passing along about the circumstances of the error?

A universal standard library error could be as simple as 

struct Error: ErrorType {
  let reason: String
}

although, I'd far prefer to add a context, using the newly updated debug literals to describe
exactly where the error sourced from. An ideal context <http://ericasadun.com/2015/08/27/capturing-context-swiftlang/> would include:

* A source location including a fully qualified module, file name and line number, shared 
  object (dsohandle), symbol, e.g. FooType.methodName(label1: _, label2: _) (with an optional 
  mangled name component), and column number (although I sincerely do not understand 
   the point of column number)
* An indicator of release or debug build
* Pre-crafted strings that combine these data into printable forms suitable for release and 
  debug output using brief, long, and exhaustive context forms.
* Decomposable elements, offering both the full context story while retaining an option
  to access and query individual components as needed.

struct Error: ErrorType {
  let reason: String
  let context: ContextType
}

further, I'd want to implement some kind of generalizable dictionary, an infoDictionary
rather than a userDictionary, that describes error circumstances and possible recovery
selectors, without being tied to the notion that the ultimate consumer <https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ErrorObjectsDomains/ErrorObjectsDomains.html#//apple_ref/doc/uid/TP40001806-CH202-CJBGAIBJ> is an NSAlert
presented to a user.

struct Error: ErrorType {
  let reason: String
  let context: ContextType
  let infoDictionary: Dictionary<String: Any>
}

-- Erica


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160306/4b66c3e3/attachment.html>


More information about the swift-evolution mailing list