检查来自Firestore Get golang sdk的错误返回代码。

huangapple go评论82阅读模式
英文:

Check error return code from Firestore Get golang sdk

问题

我正在尝试使用 golang sdk 在 firestore 中创建一个文档。

我该如何检查调用 DocumentRef.Get() 后返回的错误代码?

目前我正在检查错误是否包含 "NotFound" ... 显然不是理想的解决方法,但似乎找不到其他方法。

当前代码:

doc := firestoreClient.Collection("users").Doc(id)
userSnapshot, err := doc.Get(ctx)
var u *User	
if err != nil {
  isNotFound := strings.Contains(err.Error(), "NotFound")
  if isNotFound {
   // 创建文档
  }
}

理想情况下,我想做类似这样的操作 if err.Code == NotFound // 适当处理

或者更好的是,如果有一种正确的模式可以在 Firestore 中获取或创建一个项目(使用 golang)。

英文:

I'm trying to create a document in firestore using golang sdk

How can I check the error code returned by the call to DocumentRef.Get() ?

Right now I'm checking if the error contains "NotFound"... Definitely not ideal but can't seem to find anything else

Current Code:

doc := firestoreClient.Collection("users").Doc(id)
userSnapshot, err := doc.Get(ctx)
var u *User	
if err != nil {
  isNotFound := strings.Contains(err.Error(), "NotFound")
  if isNotFound {
   // create the document
  }
}

Ideally I would like to do something like if err.Code == NotFound // handle
appropriately

Or even better, if there's a right pattern for how to GetOrCreate an item in Firestore (using golang)

答案1

得分: 4

我刚在官方文档中找到了这个(https://pkg.go.dev/cloud.google.com/go/firestore#DocumentRef.Get):

import (
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)
status.Code(err) == codes.NotFound

谢谢你提供的指引!这里还有一个线程:https://stackoverflow.com/questions/64806911/what-is-the-idomatic-way-to-get-a-single-document-from-firestore-using-go

另一个线程:https://github.com/googleapis/google-cloud-go/issues/861

英文:

I just found this in the official docs(https://pkg.go.dev/cloud.google.com/go/firestore#DocumentRef.Get)

import (
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)
status.Code(err) == codes.NotFound

Thanks for the pointer here! https://stackoverflow.com/questions/64806911/what-is-the-idomatic-way-to-get-a-single-document-from-firestore-using-go

Another thread: https://github.com/googleapis/google-cloud-go/issues/861

huangapple
  • 本文由 发表于 2022年3月22日 15:08:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/71568083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定