新手操作,并try 了解如何访问错误详细信息.我已经创建了一个用户,现在我预计会收到一个"Email-Always-Existes"错误:

    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
    }

下面是我在调试器中看到的内容:

enter image description here

我如何处理该错误,以便从中获取代码?

推荐答案

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!

Go相关问答推荐

区分Terminal和Hook Zerolog Go中的错误级别日志(log)输出

Golang测试容器,无法使网络正常工作

使用Go使用Gorm使用外键对数据进行排序

golang有int32溢出吗?

如何使用中间件更改http请求的响应代码?

Go中的Slice[:1][0]与Slice[0]

如何使用 go 读取 RDF xml 文件中的 XML 命名空间属性

无效操作:v > max(类型参数 T 与 > 不可比较)

Golang 发送Post请求出现400错误

Go 中的 Azure JWT 验证不起作用

Gorm 在自定义字符串类型上返回 scanner 错误

Yocto 无法交叉编译 GoLang Wails 应用程序

无法从主域访问子域:无Access-Control-Allow-Origin

go-echo中如何防止+转义

Go 中的 HTTP 请求验证中间件

具有未导出字段的 struct 类型之间的转换

Golang 工作池实现意外工作

将未知长度切片的值分配给Go中的 struct ?

不理解切片和指针

防止在 Go 公用文件夹中列出目录