Created
January 10, 2017 18:52
-
-
Save karrick/5f80f3149b892badc8d6defe636ae9c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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