Docs and popular blogs suggest that Swift error handling is done using do-catch and to handle an ErrorType enumeration or an NSError instance.
Are ErrorType and NSError overflow instances mutually exclusive in a try catch block? If not, how do you implement a function that throws both?
I have associated an NSError instance with an enumeration, sort of like this, which seems to work, but is this a de facto way to return detailed error information?
enum Length : ErrorType { case NotLongEnough(NSError) case TooLong(NSError) } func myFunction() throws { throw Length.NotLongEnough(NSError(domain: "domain", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "Not long enough mate"])) } do { try myFunction() } catch Length.NotLongEnough(let error) { print("\(error)") }
This example shows how ErrorType can be passed to NSError.
do { let str = try NSString(contentsOfFile: "Foo.bar", encoding: NSUTF8StringEncoding) } catch let error as NSError { print(error.localizedDescription) }
I can not find the error forwarding that matches the ErrorType for NSString, so should we assume that this will be an instance of NSError? Of course, we could run the code to make sure, but, of course, the documents should tell us. (I appreciate that I may have read the documents incorrectly)
user1951992
source share