Simplest way to throw an error/exception with a custom message in Swift 2?

前端 未结 10 1852
走了就别回头了
走了就别回头了 2020-12-22 15:57

I want to do something in Swift 2 that I\'m used to doing in multiple other languages: throw a runtime exception with a custom message. For example (in Java):



        
相关标签:
10条回答
  • 2020-12-22 16:51

    Check this cool version out. The idea is to implement both String and ErrorType protocols and use the error's rawValue.

    enum UserValidationError: String, Error {
      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."
    }
    

    Usage:

    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
    }
    
    0 讨论(0)
  • 2020-12-22 16:55

    Simplest solution without extra extensions, enums, classes and etc.:

    NSException(name:NSExceptionName(rawValue: "name"), reason:"reason", userInfo:nil).raise()
    
    0 讨论(0)
  • 2020-12-22 16:56

    The simplest way is to make String conform to Error:

    extension String: Error {}
    

    Then you can just throw a string:

    throw "Some Error"
    

    To make the string itself be the localizedString of the error you can instead extend LocalizedError:

    extension String: LocalizedError {
        public var errorDescription: String? { return self }
    }
    
    0 讨论(0)
  • 2020-12-22 16:58

    @nick-keets's solution is most elegant, but it did break down for me in test target with the following compile time error:

    Redundant conformance of 'String' to protocol 'Error'

    Here's another approach:

    struct RuntimeError: Error {
        let message: String
    
        init(_ message: String) {
            self.message = message
        }
    
        public var localizedDescription: String {
            return message
        }
    }
    

    And to use:

    throw RuntimeError("Error message.")
    
    0 讨论(0)
提交回复
热议问题