Golang,mongodb:获取数据库错误的详细信息/代码
问题描述:
我想根据返回的数据库错误返回适当的HTTP状态代码。 例如,如果没有找到记录,我会发送404,如果它是别的 - 500,等等......Golang,mongodb:获取数据库错误的详细信息/代码
目前,我只是从mgo获得标准error
类型。 如何获得一个int错误代码,以便我可以分析它并返回相应的HTTP代码?
实施例:
func (db *DB) GetRecord() (*Person, error) {
c := db.C("people")
res := Person{}
err := c.Find(bson.M{"name": "Alexandra"}).One(&res)
if err != nil {
return nil, err
}
return &res, nil
}
所以这个函数只得到一个记录,并返回一个错误(在故障的情况下),其被螺纹连接至HTTP处理程序。
func (s *State) Index(c *gin.Context) {
res, err := s.DB.GetArticles()
if err != nil {
d := gin.H{
"error": gin.H{
"status": "404",
"title": "Get record error!",
"detail": err.Error(),
},
}
c.JSON(404, d)
}
content := gin.H{
"data": gin.H{
"type": "records",
"id": res.Id,
"attributes": gin.H{
"Phone": res.Phone,
},
},
}
c.JSON(200, content)
}
的JSON错误回复具有用于HTTP状态代码的实际DB的错误和状态字段的细节字段。 HTTP状态代码必须根据数据库错误来确定。
那么如何获得一个int错误代码的详细错误,所以我可以通过它switch
并返回正确的HTTP状态?
我可以在文档中看到QueryError
和LastError
,但我无法弄清楚如何返回它们。我想这个问题归结为使用QueryError
和LastError
类型的正确方法。
谢谢。
答
做一个错误的类型开关。在每种情况下,错误将是任何类型的错误,因此您可以访问它可能具有的任何字段,如错误消息。
func (s *State) Index(c *gin.Context) {
res, err := s.DB.GetArticles()
if err != nil {
switch err.(type){
case ErrNotFound:
d := gin.H{
"error": gin.H{
"status": "404",
"title": "Get record error!",
"detail": err.Error(),
},
}
c.JSON(404, d)
case *QueryError:
//how you want to deal with a queryError
case *LastError:
//how you want to deal with a LastError
}
}
content := gin.H{
"data": gin.H{
"type": "records",
"id": res.Id,
"attributes": gin.H{
"Phone": res.Phone,
},
},
}
c.JSON(200, content)
}
谢谢您的帮助。但它不编译。它错误了:“不可能类型切换的情况下:错误(类型错误)不能有动态类型mgo.QueryError(缺少错误方法)”任何想法?我无法相信从DB –
那里得到这些错误代码是非常困难的。它看起来像QueryError需要* QueryError和LastError需要是* LastError。我已更新代码 –
是的,谢谢。我想明白了..它现在可以工作,但我仍然无法获得这些数据库错误代码。我做的任何错误模拟,它只是返回一个字符串错误,如“找不到”。它永远不会返回'LastError'或'QuerryError'。这两个结构具有我需要的Code字段,我无法与他们联系。 –