global recover handler for golang http panic
Asked Answered
R

2

14

I want to create global err handler to send it by email.

package main

import (
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    rtr := mux.NewRouter()
    rtr.HandleFunc("/", withPanic).Methods("GET")

    http.Handle("/", rtr)
    log.Println("Listening...")

    http.ListenAndServe(":3001", http.DefaultServeMux)
}

func withPanic(w http.ResponseWriter, r *http.Request) {
    panic("somewhere here will be panic, but I don't know where exactly")
}

How to make it global. It would be easy if I know where error will occur

if err != nil {
sendMeMail(err)
}

But what to do in cases when I don't know exactly where an error will occur? So I should add a global recoverish handler. But how to do it exactly I don't know.

Update

I added defer recover to beginning of main but it never executes on requesting http://localhost:3001. So panic is not emailed.

package main

import (
    "errors"
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
            // find out exactly what the error was and set err
            var err error
            switch x := r.(type) {
            case string:
                err = errors.New(x)
            case error:
                err = x
            default:
                err = errors.New("Unknown panic")
            }
            if err != nil {
                // sendMeMail(err)
                fmt.Println("sendMeMail")
            }
        }
    }()
    rtr := mux.NewRouter()
    rtr.HandleFunc("/", withPanic).Methods("GET")

    http.Handle("/", rtr)
    log.Println("Listening...")

    http.ListenAndServe(":3001", http.DefaultServeMux)
}

func withPanic(w http.ResponseWriter, r *http.Request) {
    panic("somewhere here will be panic, but I don't know where exactly")
}
Rebus answered 26/2, 2015 at 14:58 Comment(0)
G
36

You can wrap your handlers in a recovery middleware

package main

import (
    "errors"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    m := mux.NewRouter()
    m.Handle("/", RecoverWrap(http.HandlerFunc(handler))).Methods("GET")

    http.Handle("/", m)
    log.Println("Listening...")

    http.ListenAndServe(":3001", nil)

}

func handler(w http.ResponseWriter, r *http.Request) {
    panic(errors.New("panicing from error"))
}

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

func sendMeMail(err error) {
    // send mail
}

You can take a a look at codahale recovery handler or negroni middleware for more details.

Gravely answered 26/2, 2015 at 15:44 Comment(4)
e.Error() should be err.Error()?Haynor
fixed @eyeAppsLLC.Gravely
Very neat solutionInterfuse
r := recover() hides r *http.Request from outer function. If you want to access it in recovery block - better to change the name, e.g. e := recover()Schweinfurt
M
5

I believe that is what the gorilla recovery handler is for

Minutely answered 8/8, 2018 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.