英文:
How to handle errors with firebase admin sdk for Go?
问题
你好!要获取错误的详细信息,你可以使用类型断言来检查错误类型,并从中获取代码。在你的代码中,你可以这样处理错误:
fbUser, err := s.auth.CreateUser(ctx, fbUserParams)
if err != nil {
if firebaseErr, ok := err.(*firebaseAuth.Error); ok {
// 获取错误代码
errorCode := firebaseErr.Code
// 处理特定错误
if errorCode == "email-already-exists" {
// 处理已存在的电子邮件错误
} else {
// 处理其他错误
}
} else {
// 处理非 firebaseAuth.Error 类型的错误
}
}
通过将错误断言为 *firebaseAuth.Error
类型,你可以访问 Code
属性来获取错误代码。然后,你可以根据错误代码执行相应的处理逻辑。请确保导入正确的包并使用正确的类型。
希望这可以帮助到你!如果你有任何其他问题,请随时问。
英文:
New to Go and trying to understand how to access the error details. I've already created a user, and now I'm expecting to get a "email-already-exists" error:
fbUser, err := s.auth.CreateUser(ctx, fbUserParams)
if err != nil {
return nil, errors.New("[email] already exists") // <- it could be any other error, and I want to be able to handle it
}
Here's what I see in my debugger:
How can I handle the error so that I can get the Code from it?
答案1
得分: 3
我认为你最好的选择是使用Errors.As
函数。你可以在这里了解更多信息:https://pkg.go.dev/errors#As
Google Firebase返回的错误类型是FirebaseError
,它包含两个属性:Code
和String
。你可以尝试使用以下代码片段:
fbUser, err := s.auth.CreateUser(ctx, fbUserParams)
if err != nil {
var firebaseErr *FirebaseError
if errors.As(err, &firebaseErr) {
// 在这里你可以访问"Code"和"String"
} else {
return nil, errors.New("[email] already exists")
}
}
通过这段代码,你应该能够处理你需要的内容。请注意正确导入提供FirebaseError
类型的包。也许先阅读一些Firebase文档会有所帮助。
希望这可以帮到你!
英文:
I think that the best option you have is using the Errors.As
function. You can learn more about it at here: https://pkg.go.dev/errors#As
The error returned by Google Firebase is of type FirebaseError
that involves two properties: Code
and String
. You can try with the following code snippet:
fbUser, err := s.auth.CreateUser(ctx, fbUserParams)
if err != nil {
var firebaseErr *FirebaseError
if errors.As(err, &firebaseErr) {
// here you can access "Code" and "String"
} else {
return nil, errors.New("[email] already exists")
}
}
Thanks to this code you should be able to manage what you need. Pay attention to import correctly the package that provides the type FirebaseError
. Maybe read something on the Firebase documentation first.
Hope this helps!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论