feat: add error_context label

This commit is contained in:
Kevin Franklin Kim 2025-03-07 21:10:35 +01:00
parent e179275645
commit 1bfab3a36f
No known key found for this signature in database
2 changed files with 4 additions and 60 deletions

View File

@ -1,60 +0,0 @@
package middleware
import (
"net/http"
httputils "github.com/foomo/keel/utils/net/http"
"go.uber.org/zap"
)
type (
CancelOptions struct {
Code int
}
CancelOption func(*CancelOptions)
)
// GetDefaultCancelOptions returns the default options
func GetDefaultCancelOptions() CancelOptions {
return CancelOptions{
Code: 499,
}
}
// CancelWithCode middleware option
func CancelWithCode(v int) CancelOption {
return func(o *CancelOptions) {
o.Code = v
}
}
// Cancel middleware
func Cancel(opts ...CancelOption) Middleware {
options := GetDefaultCancelOptions()
for _, opt := range opts {
if opt != nil {
opt(&options)
}
}
return CancelWithOptions(options)
}
// CancelWithOptions middleware
func CancelWithOptions(opts CancelOptions) Middleware {
return func(l *zap.Logger, name string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
done := make(chan struct{})
go func() {
next.ServeHTTP(w, r)
close(done)
}()
select {
case <-r.Context().Done():
httputils.ServerError(l, w, r, opts.Code, r.Context().Err())
case <-done:
// If handler completes normally
}
})
}
}

View File

@ -99,6 +99,10 @@ func LoggerWithOptions(opts LoggerOptions) Middleware {
l = l.With(labeler.Get()...) l = l.With(labeler.Get()...)
} }
if err := r.Context().Err(); err != nil {
l = l.With(zap.String("error_context", err.Error()))
}
switch { switch {
case opts.MinErrorCode > 0 && wr.statusCode >= opts.MinErrorCode: case opts.MinErrorCode > 0 && wr.statusCode >= opts.MinErrorCode:
l.Error(opts.Message) l.Error(opts.Message)