gpt4 book ai didi

error-handling - 如何使用 RecoverableError 重试?

转载 作者:行者123 更新时间:2023-12-04 12:45:59 24 4
gpt4 key购买 nike

在 Swift 3 中,RecoverableError protocol被介绍了,但是这里很少有关于如何使用它的文档。

这听起来像是为失败的进程提供重试功能的 native 方式,这可能非常有用。什么是如何使用它的示例?

最佳答案

您可以使用的一件事RecoverableError是 macOS 的基于文档的应用程序。

  • 创建一个新项目,macOS > Cocoa,选中“Create Document-Based Application”。
  • 定义您自己的符合 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...")
    }
    }
  • 修改data(ofType:) Document.swift 中的方法抛出错误。
    override func data(ofType typeName: String) throws -> Data {
    //throw RecoverableError
    throw MyError.documentSavingError
    }
  • 在当前的基于文档的应用程序中,您还需要一个技巧……

    创建一个新的 swift 代码来创建子类 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)
    }
    }

    当前基于文档的应用程序包装抛出 RecoverableError在平常 NSError ,所以,没有这个,自动生成 NSDocumentErrorRecoveryAttempter效果不佳。

    不要忘记修改 Info.plist 以将此类指定为其 Principal 类。
  • 构建并运行应用程序,然后在出现文档窗口时,文件 > 保存...,然后单击保存表中的保存。

    您可能会发现您的 RecoverableError正在工作...


  • 所以, RecoverableError当您的应用程序已经实现了 Error Handling Programming Guide 中描述的标准恢复功能时非常有用。 .它的介绍清楚地说明了:

    Important: The NSError class is available on both OS X and iOS. However, the error-responder and error-recovery APIs and mechanisms are available only in the Application Kit (OS X).

    关于error-handling - 如何使用 RecoverableError 重试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40352975/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com