GoLang mgo – 在 find(…).All(…) 中出现 mgo.ErrNotFound。

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

GoLang mgo - mgo.ErrNotFound for find(...).All(...)

问题

我有一段GoLang代码:

c.Find(selectQuery).All(&results)
if err == mgo.ErrNotFound {
    // 错误处理
}

这里的selectQuery值并不重要。

我从来没有收到过ErrNotFound错误。即使查询不匹配任何结果,我也没有收到ErrNotFound。我得到的是具有空属性的result变量。我应该如何修改代码来处理ErrNotFound的情况?

英文:

I have a GoLang code:

c.Find(selectQuery).All(&results)
if err == mgo.ErrNotFound {
// error handling
}

selectQuery value is not important here.

I never get error ErrNotFound. Even if the query doesn't match any results I don't get ErrNotFound. I get variable result with empty attributes. How should I change the code to handle ErrNotFound case?

答案1

得分: 8

Query.All()方法永远不会返回mgo.ErrNotFound,所以检查这个是没有意义的。如果没有结果,results的长度将为0,这样你就可以检测是否有错误:

err := c.Find(selectQuery).All(&results)
if err != nil {
    // 错误处理
    return
}
// 如果你必须检测“未找到”的情况:
if len(results) == 0 {
    // 没有结果
}

mgo.ErrNotFound通常由其他方法使用/返回,通常是那些应该操作单个文档的方法,比如Query.One()Query.Apply()

英文:

Query.All() never returns mgo.ErrNotFound, so it's useless to check for that. If there are no results, the length of results will be 0, so that's how you can detect that if there were no errors:

err := c.Find(selectQuery).All(&results)
if err != nil { {
    // error handling
    return
}
// If you must detect "not found" case:
if len(results) == 0 {
    // No results
}

mgo.ErrNotFound is used / returned by other methods, usually by those which ought to operate on a single document, such as Query.One() or Query.Apply().

huangapple
  • 本文由 发表于 2017年6月1日 16:51:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/44302790.html
匿名

发表评论

匿名网友

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

确定