SwiftUI Firebase 如何进行自定义错误处理

SwiftUI Firebase How To Do Custom Error Handling

所以我正在创建一个使用 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()
            
        }
        
    }

Authentication Documentation.

中列出了所有身份验证错误代码

以下是如何处理错误和显示您自己的错误消息的简短片段。

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

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