Created
February 26, 2019 04:47
-
-
Save masnun/8264800d3af45dff2ca34d3bce9bbe19 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.