mirror of
https://github.com/safing/portbase
synced 2025-09-02 02:29:59 +00:00
Add better handling for panics within api endpoint handlers
This commit is contained in:
parent
f3591e81c3
commit
efcea66226
1 changed files with 27 additions and 4 deletions
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue