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

问题描述 投票:0回答:2

因此,我正在创建一个使用 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()
            
        }
        
    }
firebase error-handling swiftui
2个回答
2
投票

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

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

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

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


0
投票

首先,为自定义错误消息定义一个扩展函数,如下所示 -

import Foundation
import FirebaseAuth

extension NSError {
    
    func getErrorMessage() -> String {
        
        let code = AuthErrorCode.Code(rawValue: self.code)
        
        if(code == .invalidEmail){
            return "Invalid email"
        }
        else if(code == .invalidCredential){
            return "Wrong email or password"
        }
        else if(code == .wrongPassword){
            return "Invalid password"
        }
        else if(code == .networkError)
        {
            return "Network error"
        }
        else if(code == .weakPassword){
            return "Weak Password"
        }
        else {
            return "Unknown error"
        }
        
    }
}

现在像这样调用您的 Firebase 身份验证函数 -

  func submitLoginForm(email:String, password:String) async-> Void{

       do{  
            try await Auth.auth().signIn(withEmail: email, password: password)
               
        }catch{
            let err = error as NSError
            let errorMessage = err.getErrorMessage()
            print("Error: \(errorMessage)")
        }
  }
© www.soinside.com 2019 - 2024. All rights reserved.