【发布时间】:2018-01-12 11:01:44
【问题描述】:
这里https://github.com/astaxie/build-web-application-with-golang/blob/master/en/11.1.md 描述了如何根据http 包使用自定义路由器和自定义错误类型来增强错误处理。
type appError struct {
Error error
Message string
Code int
}
type appHandler func(http.ResponseWriter, *http.Request) *appError
// custom handler catching errors
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil { // e is *appError, not os.Error.
c := appengine.NewContext(r)
c.Errorf("%v", e.Error)
http.Error(w, e.Message, e.Code)
}
}
// fetch data or return *appError
func viewRecord(w http.ResponseWriter, r *http.Request) *appError {
c := appengine.NewContext(r)
key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
record := new(Record)
if err := datastore.Get(c, key, record); err != nil {
return &appError{err, "Record not found", 404}
}
if err := viewTemplate.Execute(w, record); err != nil {
return &appError{err, "Can't display record", 500}
}
return nil
}
目的是让所有的handler在出错时返回*appError并写入到路由器的response中,所以不需要在viewRecord的代码中直接调用c.JSON(500, err) .
如何对Gin做同样的事情?
【问题讨论】:
-
这里github.com/gin-gonic/gin/issues/274我找到了类似的讨论,但仍然没有找到解决方案。
标签: http go web-applications error-handling