当 String 不符合错误时抛出的函数命中 do catch 块时如何获得正确的错误?

How to get the correct error when hitting a do catch block for a function that throws when String does not conform to Error?

import Foundation

enum ErrorScenarios: Error {
    case invalidAge
    case invalidEmail
    case incorrectData
}

func age(age:Int) throws {
    if age < 20 {
        throw ErrorScenarios.invalidAge
    }
    print("You have a valid age of \(age)")
}

extension ErrorScenarios: LocalizedError {
    var localizedDescription: String {
        switch self {
        case .incorrectData:
            return "Incorrect data provided"
        case .invalidAge:
            return "Incorrect age was provided"
        case .invalidEmail:
            return "Incorrect email provided"
        }
    }
}

这里我使用了一个 do catch 块来捕获 invalidAge 错误场景,我不太确定这是否正确?当我 运行 游乐场时,接球块永远不会被击中。

do {
    try age(age: -23)
}
catch {
    throw ErrorScenarios.invalidAge
}

这里作为 do catch 块的替代方法,我通过将其设为可选来处理错误,因此我猜不需要 do catch 块。但是,当打印结果时,它 returns Optional(() 而不是可选的 Int。如果我出错,我们将不胜感激。

let result = try? age(age: 34)
print(result)

问题是您正在抛出另一个错误,而不是使用您的 age 方法抛出的错误:

do {
    try age(age: -23)
} catch {
    if let error = error as? ErrorScenarios {
        print("ErrorScenarios:", error)  // "ErrorScenarios: Incorrect age was provided\n"
        switch error {
        case .incorrectData:
            print("invalidAge")
             case .invalidAge:
            print("invalidAge")   // "invalidAge\n"
             case .invalidEmail:
            print("invalidEmail")
        }
    } else {
        print("Error:", error)
    }
}

或者如果您更喜欢多个 catch 块:

do {
    try age(age: -23)
} catch let error as ErrorScenarios {
    print("ErrorScenarios:", error)
    switch error {
    case .incorrectData:
        print("invalidAge")
    case .invalidAge:
        print("invalidAge")
    case .invalidEmail:
        print("invalidEmail")
    }
} catch {
    print("Error:", error)
}