0

我想向自己发送电子邮件,但在页面http://localhost:3000/panic上出现错误并包含错误 url -/panic在我们的例子中。但我不知道如何从c martini.Context内部RecoverWrap方法获取 url。

package main

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

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

    m.Get("/", func(req *http.Request, res http.ResponseWriter) {
        res.Write([]byte("mainPage"))
    })

    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")
            }
            // how to get request url here
            // I want to send email with error url
            http.Error(w, "Something goes wrong", http.StatusInternalServerError)
        }
    }(w)
    c.Next()
}
4

1 回答 1

0

答案是添加req *http.Request参数func RecoverWrap(c martini.Context, req *http.Request, w http.ResponseWriter)

完整代码:

package main

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

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

    m.Get("/", func(req *http.Request, res http.ResponseWriter) {
        res.Write([]byte("mainPage"))
    })

    m.Run()
}

func RecoverWrap(c martini.Context, req *http.Request, 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")
            }

            fmt.Println("req.URL.Path")
            fmt.Println(req.URL.Path)
            http.Error(w, "Something goes wrong", http.StatusInternalServerError)
        }
    }(w)
    c.Next()
}
于 2015-03-01T04:32:10.857 回答