如何获取函数抛出的错误列表? [英] How get the list of errors thrown by a function?
问题描述
使用Swift现在,一些功能标记为 throws
,这迫使开发人员调用 do-try catch
块。
但是开发者如何知道该函数抛出的不同异常的列表?
With Swift now some functions are marked with throws
, and this force the developers to call the function inside a do - try catch
block.
But how the developer can know the list of different exceptions thrown by that function?
作为参考,这里是一行Java代码:
As reference, here is a line of Java code:
static void employeeAge(int age) throws MyExceptionA,MyExceptionB
这里很清楚异常是2 MyExceptionA
和 MyExceptionB
和开发者可以根据错误做出不同的行为。
Here is clear that the exceptions are 2 MyExceptionA
and MyExceptionB
and the developer can decide to act differently depends of the error.
我们可以在Swift上实现相同吗?
Can we achieve the same on Swift?
推荐答案
当Swift文档说一个函数 throws
时,它们意味着它会抛出一个 ErrorType
(在Cocoa API通常是一个 NSError
),而不是一个例外。
When the Swift docs says a function throws
, they mean that it throws an ErrorType
(in Cocoa APIs usually an NSError
), not an exception.
考虑以下 do-try-catch
flow for NSFileManager
的 createDirectoryAtPath
:
Consider the following do-try-catch
flow for NSFileManager
's createDirectoryAtPath
:
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
将失败,因为文档目录已经存在。记录错误
中的 dynamicType
表明它实际上是一个 NSError
object:
createDirectoryAtPath
will fail because the documents directory already exists. Logging the dynamicType
of the error
shows that it is in fact an NSError
object:
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
,你必须检查错误
,以确定抛出的错误类型以及如何处理每个错误的信息。在 NSError
的情况下,这将是其域,代码和描述。
In order to see the different types of errors a function can throw
, you would have to examine the error
for information to determine the type of error thrown, and how to handle each error. In the case of NSError
this would be its domain, code, and description.
在这种特殊情况下,该路径上已经存在一个目录,因此文件管理器无法创建新的目录。此操作可能失败的另一个原因的例子是文件管理器没有写入权限。这将是错误代码256。
In this particular case, a directory already exists at that path, so the file manager cannot create a new directory. An example of another reason why this operation could fail would be if the file manager did not have write access. That would be error code 256.
这篇关于如何获取函数抛出的错误列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!