feat: global error handler with template rendering
Some checks are pending
Cadoles/bouncer/pipeline/pr-develop Build started...
Some checks are pending
Cadoles/bouncer/pipeline/pr-develop Build started...
This commit is contained in:
@ -2,10 +2,12 @@ package director
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"forge.cadoles.com/cadoles/bouncer/internal/store"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
@ -14,6 +16,7 @@ const (
|
||||
contextKeyProxy contextKey = "proxy"
|
||||
contextKeyLayers contextKey = "layers"
|
||||
contextKeyOriginalURL contextKey = "originalURL"
|
||||
contextKeyHandleError contextKey = "handleError"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -60,3 +63,22 @@ func ctxValue[T any](ctx context.Context, key contextKey) (T, error) {
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
type HandleErrorFunc func(w http.ResponseWriter, r *http.Request, status int, err error)
|
||||
|
||||
func withHandleError(ctx context.Context, fn HandleErrorFunc) context.Context {
|
||||
return context.WithValue(ctx, contextKeyHandleError, fn)
|
||||
}
|
||||
|
||||
func HandleError(ctx context.Context, w http.ResponseWriter, r *http.Request, status int, err error) {
|
||||
err = errors.WithStack(err)
|
||||
|
||||
fn, ok := ctx.Value(contextKeyHandleError).(HandleErrorFunc)
|
||||
if !ok {
|
||||
logger.Error(ctx, err.Error(), logger.CapturedE(err))
|
||||
http.Error(w, http.StatusText(status), status)
|
||||
return
|
||||
}
|
||||
|
||||
fn(w, r, status, err)
|
||||
}
|
||||
|
Reference in New Issue
Block a user