Home > Enterprise >  SwiftUI Firebase How To Do Custom Error Handling
SwiftUI Firebase How To Do Custom Error Handling

Time:11-19

So I'm creating an app that used Firebase as the backend and I want to display the user-specific custom error messages instead of the built-in firebase error messages. How would I do this?

func signIn(withEmail email: String, password: String){
        
        Auth.auth().signIn(withEmail: email, password: password) { (result,err) in
            if let err = err {
            
                print("DEBUG: Failed to login: \(err.localizedDescription)")
                return
            }
            self.userSession = result?.user
            self.fetchUser()
            
        }
        
    }

CodePudding user response:

All of the Authentication error codes are listed in the Authentication Documentation.

Here's a quick snippet of how to handle the errors and present you own error message.

Auth.auth().signIn....() { (auth, error) in //some signIn function
  if let x = error {
      let err = x as NSError
      switch err.code {
      case AuthErrorCode.wrongPassword.rawValue:
          print("wrong password, you big dummy")
      case AuthErrorCode.invalidEmail.rawValue:
          print("invalid email - duh")
      case AuthErrorCode.accountExistsWithDifferentCredential.rawValue:
          print("the account already exists")
      default:
          print("unknown error: \(err.localizedDescription)")
      }
  } else {
      if let _ = auth?.user {
          print("authd")
      } else {
          print("no authd user")
      }
  }
}

There are many ways to code this so this is just an example.

  • Related