Golang,mongodb:获取数据库错误详情/错误代码

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

Golang, mongodb: getting database error details/codes

问题

我想根据返回的数据库错误返回适当的HTTP状态码。
例如,如果找不到记录,我会发送404,如果是其他错误,则发送500,依此类推...

目前,我只从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状态码。必须根据数据库错误确定HTTP状态码。

那么,如何获得具有int错误代码的详细错误,以便我可以通过switch语句进行处理并返回适当的HTTP状态?

我在文档中看到了QueryErrorLastError,但我无法弄清楚如何返回它们。我想这个问题归结为正确使用QueryErrorLastError类型的方法。

谢谢。

英文:

I'd like to return an appropriate HTTP status code depending on the returned DB error.
For instance, if a record not found, I'd send 404, if it is something else - 500, and so on ...

At the moment, I just get the standard error type from mgo.
How can I get an int error code so that I can analyse it and return appropriate HTTP code?

Example:

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
}

So this function just gets a record and returns an error (in case of a failure) which is threaded to HTTP handler.

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)
}

The JSON error reply has a detail field for the actual DB error and status field for the HTTP status code. HTTP status code has to be determined based on the DB error.

So how do I get a detailed error with an int error code so I can switch through it and return a proper HTTP status?

I can see the QueryError and LastError in the documentation but I cannot figure out how to return them. I suppose this question boils down to the correct way of using QueryError and LastError types.

Thank you.

答案1

得分: 1

对错误进行类型切换。在每个case语句中,错误将是相应的类型,因此您可以访问它可能具有的任何字段,比如错误消息。

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":  "获取记录错误!",
                    "detail": err.Error(),
                },
            }
            c.JSON(404, d)
       case *QueryError:
            // 处理查询错误的方式
       case *LastError:
            // 处理最后一个错误的方式

       }
    }
    content := gin.H{
        "data": gin.H{
            "type": "records",
            "id":   res.Id,
            "attributes": gin.H{
                "Phone": res.Phone,
            },
        },
    }
    c.JSON(200, content)
}
英文:

Do a type switch of the error. In each case statement, the error will be of whatever type so you can then access whatever fields it might have, like error messages.

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)

}

huangapple
  • 本文由 发表于 2016年4月15日 15:11:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/36640498.html
匿名

发表评论

匿名网友

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

确定