GAE Go —如何将GetMulti与不存在的实体密钥一起使用?
问题描述:
I've found myself needing to do a GetMulti
operation with an array of keys for which some entities exist, but some do not.
My current code, below, returns an error (datastore: no such entity
).
err := datastore.GetMulti(c, keys, infos)
So how can I do this? I'd use a "get or insert" method, but there isn't one.
我发现自己需要对键数组进行 下面的我当前的代码返回错误( 那我该怎么做呢? 我会使用“获取或插入”方法,但是没有。 p>
div> GetMulti code>操作 p>
数据存储区:没有这样的实体 code>)。 p> \ n
err:= datastore.GetMulti(c,键,信息) code> p>
答
GetMulti can return a appengine.MultiError
in this case. Loop through that and look for datastore.ErrNoSuchEntity
. For example:
if err := datastore.GetMulti(c, keys, dst); err != nil {
if me, ok := err.(appengine.MultiError); ok {
for i, merr := range me {
if merr == datastore.ErrNoSuchEntity {
// keys[i] is missing
}
}
} else {
return err
}
}
答
I know this topic is up for more than a few days, but I like to post an alternative, using type switch.
if err := datastore.GetMulti(c, keys, dst); err != nil {
switch errt := err.(type) {
case appengine.MultiError:
for ix, e := range errt {
if e == datastore.ErrNoSuchEntity {
// keys[ix] not found
} else if e != nil {
// keys[ix] have error "e"
}
}
default:
// datastore returned an error that is not a multi-error
}
}