如何使用自定义消息抛出错误消息(即ErrorType
)?
例如:
catch let error as MyError {
print(error.customMessage)
}
答案 0 :(得分:2)
我发现了这个干净的版本。我们的想法是实现String和ErrorType协议,并使用错误的rawValue。
enum UserValidationError: String, ErrorType {
case NoFirstNameProvided = "Please insert your first name."
case NoLastNameProvided = "Please insert your last name."
case NoAgeProvided = "Please insert your age."
case NoEmailProvided = "Please insert your email."
}
用法:
do {
try User.define(firstName,
lastName: lastName,
age: age,
email: email,
gender: gender,
location: location,
phone: phone)
}
catch let error as User.UserValidationError {
print(error.rawValue)
return
}