Skip to content

Commit

Permalink
feat: add x-sb-error-code header, show error code in logs (#1765)
Browse files Browse the repository at this point in the history
Adds the `x-sb-error-code` header to non-2XX responses if the error has
an error code determined. This is picked up by the request logger which
includes it in the request completed log.

Furthermore, the same header can be picked up by the API gateway
(Supabase world) without having to parse the response to include the
error code in request logs too.
  • Loading branch information
hf authored Sep 24, 2024
1 parent 6ee0091 commit ed91c59
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
6 changes: 6 additions & 0 deletions internal/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ func HandleResponseError(err error, w http.ResponseWriter, r *http.Request) {
output.Message = e.Message
output.Payload.Reasons = e.Reasons

w.Header().Set("x-sb-error-code", output.ErrorCode)

if jsonErr := sendJSON(w, output.HTTPStatus, output); jsonErr != nil && jsonErr != context.DeadlineExceeded {
log.WithError(jsonErr).Warn("Failed to send JSON on ResponseWriter")
}
Expand All @@ -243,6 +245,10 @@ func HandleResponseError(err error, w http.ResponseWriter, r *http.Request) {
log.WithError(e.Cause()).Info(e.Error())
}

if e.ErrorCode != "" {
w.Header().Set("x-sb-error-code", e.ErrorCode)
}

if apiVersion.Compare(APIVersion20240101) >= 0 {
resp := HTTPErrorResponse20240101{
Code: e.ErrorCode,
Expand Down
11 changes: 9 additions & 2 deletions internal/observability/request-logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,17 @@ type logEntry struct {
}

func (e *logEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
entry := e.Entry.WithFields(logrus.Fields{
fields := logrus.Fields{
"status": status,
"duration": elapsed.Nanoseconds(),
})
}

errorCode := header.Get("x-sb-error-code")
if errorCode != "" {
fields["error_code"] = errorCode
}

entry := e.Entry.WithFields(fields)
entry.Info("request completed")
e.Entry = entry
}
Expand Down

0 comments on commit ed91c59

Please sign in to comment.