Add better handling for panics within api endpoint handlers

This commit is contained in:
Daniel 2022-06-21 16:59:41 +02:00
parent f3591e81c3
commit efcea66226

View file

@ -3,9 +3,11 @@ package api
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
"runtime/debug"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -226,13 +228,34 @@ func (mh *mainHandler) handle(w http.ResponseWriter, r *http.Request) error {
w.Header().Add("Vary", "Origin") w.Header().Add("Vary", "Origin")
} }
// Handle request. // Check if we have a handler.
if handler != nil { if handler == nil {
handler.ServeHTTP(lrw, r)
} else {
http.Error(lrw, "Not found.", http.StatusNotFound) http.Error(lrw, "Not found.", http.StatusNotFound)
return nil
} }
// Format panics in handler.
defer func() {
if panicValue := recover(); panicValue != nil {
if devMode() {
http.Error(
lrw,
fmt.Sprintf(
"Internal Server Error: %s\n\n%s",
panicValue,
debug.Stack(),
),
http.StatusInternalServerError,
)
} else {
http.Error(lrw, "Internal Server Error.", http.StatusInternalServerError)
}
}
}()
// Handle with registered handler.
handler.ServeHTTP(lrw, r)
return nil return nil
} }