duanhui4160 2015-02-28 10:15
浏览 7
已采纳

马提尼酒恢复任何恐慌

I want to wire RecoverWrap to all handlers of martini routes to make any panic be finished by code inside RecoverWrap.

I tried to do it like m.Use(RecoverWrap) but do not know how to do it exactly, it fails on compile.

package main

import (
    "errors"
    "github.com/go-martini/martini"
    "net/http"
)

func main() {
    m := martini.Classic()
    //m.Use(RecoverWrap)
    m.Get("/", func() {
        panic("some panic")
    })

    m.Run()
}

func RecoverWrap(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        var err error
        defer func() {
            r := recover()
            if r != nil {
                switch t := r.(type) {
                case string:
                    err = errors.New(t)
                case error:
                    err = t
                default:
                    err = errors.New("Unknown error")
                }

                http.Error(w, "Something goes wrong", http.StatusInternalServerError)
            }
        }()
        h.ServeHTTP(w, req)
    })
}
  • 写回答

1条回答 默认 最新

  • doujuan2688 2015-02-28 15:54
    关注

    Middleware handlers in Martini do not get to "wrap" other handler calls, so http.Handler is not found by the injector.

    What you can do is use context.Next():

    package main
    
    import (
    "errors"
    "github.com/go-martini/martini"
    "net/http"
    )
    
    func main() {
        m := martini.Classic()
        m.Use(RecoverWrap)
        m.Get("/", func() {
            panic("some panic")
            })
    
        m.Run()
    }
    
    func RecoverWrap(c martini.Context, w http.ResponseWriter) {
        var err error
        defer func(w http.ResponseWriter) {
            r := recover()
            if r != nil {
                switch t := r.(type) {
                case string:
                    err = errors.New(t)
                case error:
                    err = t
                default:
                    err = errors.New("Unknown error")
                }
                http.Error(w, "Something goes wrong", http.StatusInternalServerError)
            }
            }(w)
        c.Next()
    }
    

    You will have to make sure that your error handler is the first middleware registered, or those handlers running before will not be caught.

    Actually, the same method is implemented in martini.Recovery:

    https://github.com/go-martini/martini/blob/6241001738f6e1b1ea7c4a4089195e1b0681609a/recovery.go#L115

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题