如何使用 RecoverableError 进行重试?

7
在Swift 3中,引入了可恢复错误协议,但是关于如何使用它的文档非常少。
这听起来像是一种本地方式为失败的进程提供重试功能,这可能非常有用。有没有一个示例可以说明如何使用它?
1个回答

2

您可以在 macOS 的基于文档的应用程序中利用 RecoverableError

  1. Create a new project, macOS > Cocoa, checking "Create Document-Based Application".

  2. 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...")
        }
    }
    
  3. 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
    }
    
  4. 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.

  5. 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)中可用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接