Skip to content

Commit eefe5bf

Browse files
hfcemalkilic
authored andcommitted
feat: add x-sb-error-code header, show error code in logs (#1765)
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.
1 parent adbb4ec commit eefe5bf

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

internal/api/errors.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,8 @@ func HandleResponseError(err error, w http.ResponseWriter, r *http.Request) {
226226
output.Message = e.Message
227227
output.Payload.Reasons = e.Reasons
228228

229+
w.Header().Set("x-sb-error-code", output.ErrorCode)
230+
229231
if jsonErr := sendJSON(w, output.HTTPStatus, output); jsonErr != nil && jsonErr != context.DeadlineExceeded {
230232
log.WithError(jsonErr).Warn("Failed to send JSON on ResponseWriter")
231233
}
@@ -243,6 +245,10 @@ func HandleResponseError(err error, w http.ResponseWriter, r *http.Request) {
243245
log.WithError(e.Cause()).Info(e.Error())
244246
}
245247

248+
if e.ErrorCode != "" {
249+
w.Header().Set("x-sb-error-code", e.ErrorCode)
250+
}
251+
246252
if apiVersion.Compare(APIVersion20240101) >= 0 {
247253
resp := HTTPErrorResponse20240101{
248254
Code: e.ErrorCode,

internal/observability/request-logger.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,17 @@ type logEntry struct {
6969
}
7070

7171
func (e *logEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
72-
entry := e.Entry.WithFields(logrus.Fields{
72+
fields := logrus.Fields{
7373
"status": status,
7474
"duration": elapsed.Nanoseconds(),
75-
})
75+
}
76+
77+
errorCode := header.Get("x-sb-error-code")
78+
if errorCode != "" {
79+
fields["error_code"] = errorCode
80+
}
81+
82+
entry := e.Entry.WithFields(fields)
7683
entry.Info("request completed")
7784
e.Entry = entry
7885
}

0 commit comments

Comments
 (0)