Skip to content

Instantly share code, notes, and snippets.

@masnun
Created February 26, 2019 04:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save masnun/8264800d3af45dff2ca34d3bce9bbe19 to your computer and use it in GitHub Desktop.
Save masnun/8264800d3af45dff2ca34d3bce9bbe19 to your computer and use it in GitHub Desktop.
package middlewares
import (
"encoding/json"
"fmt"
"net/http"
)
func Recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
err := recover()
if err != nil {
fmt.Println(err) // May be log this error? Send to sentry?
jsonBody, _ := json.Marshal(map[string]string{
"error": "There was an internal server error",
})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
w.Write(jsonBody)
}
}()
next.ServeHTTP(w, r)
})
}
@DeadlySurgeon
Copy link

16 months late, but move lines 17-19 up between 9 and 10. You don't need to call Marshal every time, and also it would be a good idea to check the error incase it fails, however unlikely. Even if this is a general POC, it would be good idea to practice good habits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment