如何从异常中获取自定义消息?

时间:2020-06-25 10:42:16

标签: swift exception

我定义了一堆这样的自定义错误:

enum FilesystemError: Error {
    case cannotMove(String)
    case cannotDelete(String)
}

enum MediaError: Error {
    case cannotRecordVideo(String)
    case cannotLoadPhoto(String)
}

现在,如果引发错误,我将使用此辅助功能将其呈现给用户:

public func presentErrorAlert(presentingViewController: UIViewController, error: Error) {
    let title: String
    let message: String
    if let error = error as? FilesystemError {
        switch(error) {
        case .cannotMove(let msg):
            title = "Failed to move"
            message = msg
        case .cannotDelete(let msg):
            title = "Failed to delete"
            message = msg
        }
    }
    else if let error = error as? MediaError {
        switch(error) {
        case .cannotLoadPhoto(let msg):
            title = "Failed to load photo"
            message = msg
        case .cannotRecordVideo(let msg):
            title = "Failed to record video"
            message = msg
        }
    }
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
    presentingViewController.present(alert, animated: true, completion: nil)
}

我的代码中有很多错误,并且发生了太多“消息= msg”。感觉必须有一种更简单的方法来执行此操作。有什么想法可以优雅地规避吗?

1 个答案:

答案 0 :(得分:0)

让我们定义:

protocol ErrorFormattable: Error {
    var errorTitle: String { get }
    var errorMessage: String { get }
}

使您的错误类型符合ErrorFormattable。然后在presentErrorAlert中,只需检查:

if let error = error as? ErrorFormattable {
    title = error.errorTitle
    message = error.errorMessage
}
相关问题