Stayin' Alive: Log & recover from web server panics (#2072)

* log webserver panics
* move panic handling to separate func
This commit is contained in:
Doug Lauder 2022-01-10 15:33:05 -05:00 committed by GitHub
parent 36f66e7ea5
commit 855ea70a44
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -7,6 +7,7 @@ import (
"io/ioutil"
"net/http"
"path/filepath"
"runtime/debug"
"strconv"
"strings"
"time"
@ -65,6 +66,7 @@ func NewAPI(app *app.App, singleUserToken string, authService string, logger *ml
func (a *API) RegisterRoutes(r *mux.Router) {
apiv1 := r.PathPrefix("/api/v1").Subrouter()
apiv1.Use(a.panicHandler)
apiv1.Use(a.requireCSRFToken)
apiv1.HandleFunc("/workspaces/{workspaceID}/blocks", a.sessionRequired(a.handleGetBlocks)).Methods("GET")
@ -113,6 +115,23 @@ func (a *API) RegisterAdminRoutes(r *mux.Router) {
r.HandleFunc("/api/v1/admin/users/{username}/password", a.adminRequired(a.handleAdminSetPassword)).Methods("POST")
}
func (a *API) panicHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if p := recover(); p != nil {
a.logger.Error("Http handler panic",
mlog.Any("panic", p),
mlog.String("stack", string(debug.Stack())),
mlog.String("uri", r.URL.Path),
)
a.errorResponse(w, r.URL.Path, http.StatusInternalServerError, "", nil)
}
}()
next.ServeHTTP(w, r)
})
}
func (a *API) requireCSRFToken(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !a.checkCSRFToken(r) {