From efcea66226cec6ca97b28a0748bfe456f3b8b997 Mon Sep 17 00:00:00 2001 From: Daniel Date: Tue, 21 Jun 2022 16:59:41 +0200 Subject: [PATCH] Add better handling for panics within api endpoint handlers --- api/router.go | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/api/router.go b/api/router.go index bdc24c3..71502c3 100644 --- a/api/router.go +++ b/api/router.go @@ -3,9 +3,11 @@ package api import ( "context" "errors" + "fmt" "net/http" "net/url" "path" + "runtime/debug" "strings" "sync" "time" @@ -226,13 +228,34 @@ func (mh *mainHandler) handle(w http.ResponseWriter, r *http.Request) error { w.Header().Add("Vary", "Origin") } - // Handle request. - if handler != nil { - handler.ServeHTTP(lrw, r) - } else { + // Check if we have a handler. + if handler == nil { 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 }