Swift:无法通过关联数据捕获特定的错误情况

时间:2019-02-06 04:55:21

标签: swift exception-handling jsondecoder

我设置的自定义JSONDecoder.dateDecodingStrategy如果日期格式不正确,则会抛出DecodingError.dataCorruptedError

decoder.dateDecodingStrategy = .custom { (decoder) -> Date in
    let container = try decoder.singleValueContainer()
    let dateString = try container.decode(String.self)
    let date = /* do magic date manipulation here */

    if let date = date {
        return date
    } else {
        throw DecodingError.dataCorruptedError(in: container,
                                               debugDescription: "foo")
    }
}

但是,我似乎无法为此特定catch类型编写DecodingError子句。我尝试过

} catch DecodingError.dataCorruptedError(let container, let debugDescription) {

} catch DecodingError.dataCorruptedError(_, _) {

两者都声明为"Argument labels '(_:, _:)' do not match any available overloads."

完全忽略相关数据,例如

} catch DecodingError.dataCorruptedError {

带有"Expression pattern of type '_' cannot match values of type 'Error'."

的桶

所以我尝试了另一种方法,即

} catch let error as DecodingError {
    switch error {
    case .dataCorruptedError(_, _):

但这也无法编译,说明为"Pattern cannot match values of type 'DecodingError'."

我肯定会错过一些非常简单的东西,但是呢?

2 个答案:

答案 0 :(得分:1)

DecodingError.dataCorruptedError(in:debugDescription:)DecodingError之上的静态函数,该函数返回.dataCorrupted的大小写。因此,您的catch语句应如下所示:

} catch DecodingError.dataCorrupted(let context) {

您应该能够从上下文中提取一些信息,如果需要更多信息,则可能需要专用的错误类型。

答案 1 :(得分:0)

出现"Pattern cannot match values of type 'DecodingError'."错误(和其他错误)的原因是.dataCorruptedError(_, _)不是枚举,而是静态函数:

public static func dataCorruptedError(in container: UnkeyedDecodingContainer, debugDescription: String) -> DecodingError

要处理DataCorrupted中的switch错误,您需要使用可用的枚举大小写,例如:

catch let error as DecodingError {
    switch error {
    case .dataCorrupted:
        debugPrint("Data corrupted Custom Message")
    default: ()
    }
}