2015-10-09 36 views
0

我有這樣的自定義錯誤類:swift2如何打印錯誤消息在catch

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

回答

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 
}