0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swift6 handle error, Typed Throws sample code

Posted at
enum ValidationError: Error {
     case invalidInput
     case missingInput
     case alreadyInUse
}

extension ValidationError: LocalizedError {
    var errorDescription: String? {
    switch self {
    case .invalidInput:
        return "xxxxx"
    case .missingInput:
        return "The username cannot be empty"
    case .alreadyInUse:
        return "This username is already in use. Please try again"
    }
}

class InputValidator {
    func validateWithTypedThrow(_ input: String) throws(ValidationError) {
        guard !input.isEmpty else { throw .missingInput }
        guard input.count > 2 else { throw .invalidInput }
        guard !existingUsernames.contains(input) else { throw .alreadyInUse }
    }
}


// Event
Button("Validate") {
    do throws(ValidationError) {
        try validator.validateWithTypedThrow(username)
        self.errorMessage = nil
        self.successMessage = "Validation successful!"
    } catch {
        self.errorMessage = error.localizaedDescription

        switch error {
        case .invalidInput:
            break // do something ex) call api
        case .missingInput:
            break // present alert
        case .alreadyInUse:
            break // do something
        }
    } /* catch let error as ValidationError {
    
    } */
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?