首页 > 解决方案 > SwiftUI Firebase 如何进行自定义错误处理

问题描述

所以我正在创建一个使用 Firebase 作为后端的应用程序,我想显示用户特定的自定义错误消息,而不是内置的 firebase 错误消息。我该怎么做?

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()
            
        }
        
    }

标签: firebaseerror-handlingswiftui

解决方案


所有身份验证错误代码都列在身份验证文档中。

以下是如何处理错误并显示您自己的错误消息的快速片段。

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")
      }
  }
}

有很多方法可以对此进行编码,因此这只是一个示例。


推荐阅读