Skip to content

Instantly share code, notes, and snippets.

@karrick
Created January 10, 2017 18:52
Show Gist options
  • Save karrick/5f80f3149b892badc8d6defe636ae9c3 to your computer and use it in GitHub Desktop.
Save karrick/5f80f3149b892badc8d6defe636ae9c3 to your computer and use it in GitHub Desktop.
// PanicHandler returns a new http.Handler that catches a panic caused by the specified
// http.Handler, and responds with an appropriate http status code and message.
func PanicHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
var text string
switch t := r.(type) {
case error:
text = t.Error()
case string:
default:
text = fmt.Sprintf("%v", r)
}
http.Error(w, http.StatusText(http.StatusInternalServerError)+": "+text, http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment