httprouter icon indicating copy to clipboard operation
httprouter copied to clipboard

Catching Exception for the PanicHandler

Open jeffreyyong opened this issue 7 years ago • 5 comments

Hi,

I'm wondering what is the best way to implement catching the error returned by the PanicHandler. Especially if I want to log the error to something like Sentry. What is the best way of catching panics? Thanks

jeffreyyong avatar Sep 19 '17 12:09 jeffreyyong

Hello,

I'm interresting by the answer too. Currently I'm not using the PanicHandler from Router but a custom handler at the top.

func Panic(next httprouter.Handle) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		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")
				}
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(fmt.Sprintf("500 - %s", err)))
			}
		}()
		next(w, r, ps)
	}
}

manawasp avatar Oct 09 '17 21:10 manawasp

Hi,

Not sure why you needed that, this worked for me just fine:

func dieHard(w http.ResponseWriter, r *http.Request, err interface{}) {
	log.Println(r.URL.Path, err)
	w.WriteHeader(http.StatusInternalServerError)
}

router.PanicHandler = dieHard

alexaandru avatar Nov 03 '17 13:11 alexaandru

hi, Thanks, but how do i log the panic from dieHad method? I meant with stack trace?

abhi-illuminasy avatar Jan 06 '19 11:01 abhi-illuminasy

We can collect the panic stack trace using runtime/debug. Like,

 func dieHard(w http.ResponseWriter, r *http.Request, err interface{}) {
   log.Println(r.URL.Path, string(debug.Stack())) // Collecting panic trace
   debug.PrintStack() // or we can use PrintStack
   w.WriteHeader(http.StatusInternalServerError)
}

sharmendran avatar Jun 18 '20 17:06 sharmendran

Stack trace alternative

buf := make([]byte, 4*1024)
runtime.Stack(buf, true)
fmt.Printf("%s", buf)

azlan avatar Aug 27 '22 03:08 azlan