这听起来像是一种本地方式为失败的进程提供重试功能,这可能非常有用。有没有一个示例可以说明如何使用它?
您可以在 macOS 的基于文档的应用程序中利用 RecoverableError
。
Create a new project, macOS > Cocoa, checking "Create Document-Based Application".
Define your own Error type conforming to RecoverableError
.
enum MyError {
case documentSavingError
//...
}
extension MyError: RecoverableError {
var recoveryOptions: [String] {
return [
"Retry", "Ignore"
]
}
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool {
if recoveryOptionIndex == 0 {//for "Retry"
var result = false
switch self {
case .documentSavingError:
//Attempt "Retry" recovery for the failed operation, and return the result
//...
print("assume recovery attempt successfully finished...")
result = true
//...
}
return result
} else if recoveryOptionIndex == 1 {//for "Ignore"
return true
}
fatalError("something wrong...")
}
}
Modify the data(ofType:)
method in Document.swift as to throw the error.
override func data(ofType typeName: String) throws -> Data {
//throw RecoverableError
throw MyError.documentSavingError
}
You need one more trick in the current Document-based application...
Create a new swift code to subclass NSApplication
.
import AppKit
@objc(Application)
class Application: NSApplication {
override func presentError(_ error: Error, modalFor window: NSWindow, delegate: Any?, didPresent didPresentSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
//print(error)
let underlyingError = (error as NSError).userInfo[NSUnderlyingErrorKey] as? Error ?? error
//print(underlyingError)
super.presentError(underlyingError, modalFor: window, delegate: delegate, didPresent: didPresentSelector, contextInfo: contextInfo)
}
}
The current Document-based application wraps thrown RecoverableError
in a usual NSError
, so, without this, automatically generated NSDocumentErrorRecoveryAttempter
does not work well.
Do not forget to modify the Info.plist to designate this class as its Principal class.
Build and run the app, then when a document window is presented, File > Save..., and click Save in the save sheet.
You may find how your RecoverableError
is working...
因此,当您的应用程序已经实现了Error Handling Programming Guide中描述的标准恢复功能时,RecoverableError
非常有用。它的介绍清楚地说明:
重要提示:
NSError
类在OS X和iOS上都可用。但是,错误响应器和错误恢复API和机制仅在应用程序套件(OS X)中可用。