Skip to content

Commit

Permalink
feat(http): ✨ add structured logging for errors
Browse files Browse the repository at this point in the history
  • Loading branch information
paologaleotti committed Dec 13, 2024
1 parent 8fcc22c commit a7e4ba7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
10 changes: 7 additions & 3 deletions pkg/httpx/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"

"github.com/go-chi/render"
"github.com/rs/zerolog/log"
)

type ApiError struct {
Expand Down Expand Up @@ -36,16 +37,19 @@ type ApiErrorMap map[error]ApiError
//
// In a handler, remember to return right after calling this function to prevent further processing.
func RenderError(w http.ResponseWriter, r *http.Request, errMap ApiErrorMap, err error) {
apiErr := ApiError{}
apiErr := ErrUnkownInternal

for k, v := range errMap {
if errors.Is(err, k) {
apiErr = v
break
} else {
apiErr = ErrUnkownInternal
}
}

if apiErr == ErrUnkownInternal {
log.Error().Err(err).Msg("Unhandled error")
}

render.Status(r, apiErr.Status)
render.JSON(w, r, apiErr.With(err))
}
Expand Down
3 changes: 1 addition & 2 deletions pkg/httpx/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ func LoggerMiddleware(next http.Handler) http.Handler {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)

// TODO level error for errors
log.Info().
Stringer("url", r.URL).
Stringer("path", r.URL).
Str("method", r.Method).
Int("status", ww.Status()).
Dur("duration", time.Since(startTime)).
Expand Down

0 comments on commit a7e4ba7

Please sign in to comment.