Skip to main content

Julia Evans

« back to all TILs

a Go middleware to recover from panics

I’ve been reading Let’s Go by Alex Edwards and one of my favourite tips from the book is to write a HTTP middleware to recover from panics, something like this:

func (app *application) recoverPanic(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    defer func() {
      if err := recover(); err != nil {
        w.Header().Set("Connection", "close")
        fmt.Println(err)
        debug.PrintStack() // from "runtime/debug"
        app.serverError(w, fmt.Errorf("%s", err))
      }
    }()
    next.ServeHTTP(w, r)
  })
}

Previously my webserver would just crash if there was a panic (not even returning an error!) and I think this is better.