如何得到函数抛出的错误列表?
使用Swift现在一些函数被标记为throws
,这迫使开发人员在do - try catch
块中调用函数。 但是,开发人员如何知道该函数引发的不同exception列表呢?
作为参考,这里是一行Java代码:
static void employeeAge(int age) throws MyExceptionA,MyExceptionB
这里很明显,exception是2 MyExceptionA
和MyExceptionB
,开发人员可以决定采取不同的行为取决于错误。
我们可以在Swift上做到这一点吗?
当Swift文档说函数throws
,它们意味着抛出一个ErrorType
(在Cocoa API中通常是一个NSError
),而不是一个例外。
考虑下面的NSFileManager
的createDirectoryAtPath
do-try-catch
stream程:
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] do { try NSFileManager.defaultManager().createDirectoryAtPath(documentsPath, withIntermediateDirectories: false, attributes: nil) } catch { // 'error' variable automatically populated print(error) print(error.dynamicType) }
由于文档目录已经存在, createDirectoryAtPath
将失败。 loggingerror
的dynamicType
显示它实际上是一个NSError
对象:
Error Domain=NSCocoaErrorDomain Code=516 "The file “Documents” couldn't be saved in the folder “35B0B3BF-D502-4BA0-A991-D07568AB87C6” because a file with the same name already exists." UserInfo={NSFilePath=/Users/jal/Library/Developer/CoreSimulator/Devices/E8A35774-C9B7-42F0-93F1-8103FBBC7118/data/Containers/Data/Application/35B0B3BF-D502-4BA0-A991-D07568AB87C6/Documents, NSUnderlyingError=0x7fa88bd14410 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}} NSError
为了查看函数可能throw
的不同types的错误,您必须检查error
信息以确定抛出错误的types以及如何处理每个错误。 在NSError
的情况下,这将是它的域名,代码和描述。
在这种情况下,path中已经存在一个目录,所以文件pipe理器不能创build一个新的目录。 如果文件pipe理器没有写入权限,那么这个操作可能会失败的另一个原因的一个例子是。 这将是错误代码256。
我有和OP一样的问题。 既然没有人真正回答这个问题(我也是),我的贡献在这里。
在Swift 3和Xcode 8.3.3中,你可以这样做来处理个别exception。 下面我会给你一个FileManager的例子。
首先你将只有一个catch块来捕捉方法抛出的错误。 那么你会把这个错误作为一个NSError。 与Swift中的错误协议相反,NSError是一个REAL错误类。 然后你可以在switch语句中提取错误的代码。 你将不得不知道该方法抛出错误的域,然后在相应的头文件中find错误代码。
在我下面的例子中,文件相关的错误在NSCocoaErrorDomain中抛出,这些错误代码在Foundation / FoundationErrors.h中定义/列出。 在我的电脑里,他们位于
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Versions/C/Headers/FoundationErrors.h
为macOS应用程序和
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/Foundation.framework/Headers/
为iPhone应用程序。
所以这里是一个例子:
let home = FileManager.default.homeDirectoryForCurrentUser let file = home.appendingPathComponent("file") do { let loadedString = try String(contentsOf: file) } catch { let realError = error as NSError // As weird as it looks, Xcode actually wants this forced conversion print(realError.localizedDescription) switch realError.code { case 257: // No permission handleNoPermission() case 260: // File not found handleFileNotFound() default: handleUndefinedError() } }
.localizedDescription
在用户的语言中包含一个用户友好的消息。 如果上面没有find文件,打印: The file “file” couldn't be opened because there is no such file.
用英语。 它的意思是直接用在你给用户的错误对话框中。
您也可以在这里find关于每个域引发的错误的更多信息: https : //developer.apple.com/library/content/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ErrorObjectsDomains/ErrorObjectsDomains.html
你在catch之后编写一个模式来表示这个子句可以处理的错误。
do { try expression statements } catch pattern 1 { statements } catch pattern 2 where condition { statements }
请参阅使用“捕获Swift编程语言”处理错误
- 我怎样才能从NSURLSession.sharedSession()。dataTaskWithRequest获取数据
- 无法执行命令:分段错误:11 swift frontend命令由于信号失败(使用-v查看调用)
- UITextView专注,但用户触摸UICollectionViewCell。 隐藏键盘并运行didSelectItemAtIndexPath
- Firebase观察types.childAdded每次检索我的所有信息。 请协助
- 即使“plist”中的“UIBackgroundModes”中存在“voip”,iOS设备在iOS10中重启设备后也不会自动启动
- 从目标c到快速
- Swift – 简单的if语句中的意外错误
- 用于保存核心数据的NSPersistentContainer并发性
- Swift2:不能调用types为'NSString'的初始值设定项