簡體   English   中英

Swift中具有單個泛型函數的多種錯誤類型的泛型錯誤處理

[英]Generic error handling for multiple error type with single generic function in Swift

我有一個針對RebloodError通用類型的handleError函數。 我有兩種類型的錯誤枚舉(InitialError和MainError)符合RebloodError協議(符合Error協議)。 這是細節。

InitialError

enum InitialError: RebloodError {
    // Some Error Cases inside
}

MainError

enum MainError: RebloodError {
    // Some Error Cases inside
}

RebloodError

protocol RebloodError: Error { }

錯誤處理程序

@discardableResult func handleError<T: RebloodError>(_ error: T) -> Bool {
    let title = "Something Might Be Wrong"

    switch error {
    case .anErrorCase:
        presentErrorAlert(title: title, message: "Please Sign In to continue ", completionHandler: {
            // TODO: Go to sign in from here
        })
        return true


    default:
        presentErrorAlert(title: title, message: "Please contact support or try to relaunch the app", completionHandler: {
            exit(0)
        })
        return false
    }
}

presentErrorAlert是我的自定義函數,用於呈現UIAlertController以顯示錯誤警報。

在我的情況下,是否有最佳方法來處理通用函數的多種類型的錯誤?

我建議為RebloodError添加一個通用接口以滿足您的錯誤處理需求,並在您的具體錯誤類型中實現該接口:

protocol RebloodError: Error {
  var alertTitle: String { get }
  var alertMessage: String { get }
  func handle()
}

enum MainError: RebloodError {
  case foo
  case bar

  var alertTitle: String {
    switch self {
    case .foo: return "Foo!"
    case .bar: return "Bar!"
    }
  }      

  var alertMessage: String { ... }

  func handle() {
     switch self {
      case .foo: exit(0)
      default: ()
     }
  }
}

在您的處理代碼中,您可以使用此接口獲取所需的所有信息,該錯誤將知道該怎么做:

func handleError<T: RebloodError>(_ error: T) -> Bool {
  presentErrorAlert(title: error.alertTitle, message: error.alertMessage, completionHandler: { error.handle() })
}

RebloodError.handle函數當然僅限於在沒有任何上下文信息的情況下執行它可以執行的操作(例如,彈出視圖控制器)。 如果需要的話,事情會變得更加復雜:例如,您可以將一些上下文對象傳遞給方法(請記住,調用時您並不知道它是哪種具體類型,因此還需要一個通用的上下文接口); 或讓RebloodError.handle返回一個命令對象,然后在調用代碼中對其進行解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM