swift2如何在catch中打印错误消息

时间:2015-10-09 16:45:35

标签: ios swift swift2

我有这个自定义错误类:

enum RegistrationError :ErrorType{
    case PaymentFail
    case InformationMissed
    case UnKnown
}

我定义了一个这样的函数:

    func register(studentNationalID: Int)  throws -> Int {
    // do my business logic then:
    if studentNationalID == 100 {
        throw RegistrationError.UError(message: "this is cool")
    }

    if studentNationalID == 10 {
        throw RegistrationError.InformationMissed
    }
    return 0
}

我将这个函数称为:

do{
    let s = try register(100)
    print("s = \(s)")
} catch  RegistrationError.UError {
    print("It is error")
}

我的问题是如何打印我抛出异常时抛出的错误消息?

我在Swift2上

1 个答案:

答案 0 :(得分:2)

如果您收到错误信息,可以打印如下信息:

do{
    let s = try register(100)
    print("s = \(s)")
} catch  RegistrationError.UError (let message){
    print("error message = \(message)") // here you will have your actual message
}

但即使您没有抛出任何消息,您仍然无法捕获消息,这就是错误的类型:

do{
    let s = try register(10)
    print("s = \(s)")
} catch  RegistrationError.UError (let message){
    print("error message = \(message)")
}
catch (let message ){
    print("error message = \(message)") //here the message is: InformationMissed
}