How to find the kind of errors a method may throw and catch them in Swift [duplicate] How to find the kind of errors a method may throw and catch them in Swift [duplicate] swift swift

How to find the kind of errors a method may throw and catch them in Swift [duplicate]


NSError automatically bridges to ErrorType where the domain becomes the type (e.g. NSCocoaErrorDomain becomes CocoaError) and the error code becomes the value (NSFileReadNoSuchFileError becomes .fileNoSuchFile)

import Foundationlet docsPath = "/file/not/found"let fileManager = FileManager()do {    let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath)} catch CocoaError.fileNoSuchFile {    print("No such file")} catch let error {    // other errors    print(error.localizedDescription)}

As for knowing which error can be returned by a specific call, only the documentation can help. Almost all Foundation errors are part of the CocoaError domain and can be found in FoundationErrors.h (though there are some rare bugs where Foundation can also sometimes return POSIX errors under NSPOSIXErrorDomain) but these ones might not have been fully bridged so you will have to fall back on managing them at the NSError level.

More information can be found in « Using Swift with Cocoa and Objective-C (Swift 2.2) »


It will return NSError:

let fileManager = NSFileManager()do {    let docsArray = try fileManager.contentsOfDirectoryAtPath("/")} catch let error as NSError {    // handle errors    print(error.localizedDescription)    // The file “Macintosh HD” couldn’t be opened because you don’t have permission to view it.}


What your'e asking in the "update" part is not possible.It's the throwing function decision to let you know what it's may throw, or not to show it, and then you need to handle a generic error.

A lot of functions do reveal information about the thrown errors - for example:

func startVPNTunnel() throwsDescription Start the process of connecting the VPNtrue if the process of connecting the VPN started successfully, false if an error occurred.Parameters  error   A pointer to a pointer to an NSError object. If specified and the VPN connection process cannot be started due to an error, this parameter will be set to point to an NSError object containing details about the error. See NEVPNManager Class Reference for a list of possible errors.

Edit: a possible reason for this - that's way, the throwing function can change the errors it's throws, and all the code that catch those error would still be valid.