Skip to content

Commit

Permalink
add request id to api error
Browse files Browse the repository at this point in the history
  • Loading branch information
udsamani committed Sep 11, 2024
1 parent af77b2f commit 3548a73
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
7 changes: 7 additions & 0 deletions pkg/models/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ func (ec ErrorCode) Component() string {
return ec.component
}

func (ec ErrorCode) String() string {
if ec.httpStatusCode == 0 {
return fmt.Sprintf("%s-500", ec.component)
}
return fmt.Sprintf("%s-%d", ec.component, ec.httpStatusCode)
}

// BaseError is a custom error type in Go that provides additional fields
// and methods for more detailed error handling. It implements the error
// interface, as well as additional interfaces for providing a hint,
Expand Down
3 changes: 3 additions & 0 deletions pkg/publicapi/apimodels/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ type APIError struct {
// message is a short, human-readable description of the error.
// it should be concise and provide a clear indication of what went wrong.
Message string `json:"message"`

// RequestID is the request ID of the request that caused the error.
RequestID string `json:"request_id"`
}

// NewAPIError creates a new APIError with the given HTTP status code and message.
Expand Down
3 changes: 3 additions & 0 deletions pkg/publicapi/middleware/error_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ func CustomHTTPErrorHandler(err error, c echo.Context) {
message = "internal server error"
}

requestID := c.Request().Header.Get(echo.HeaderXRequestID)

// Don't override the status code if it is already been set.
// This is something that is advised by ECHO framework.
if !c.Response().Committed {
Expand All @@ -38,6 +40,7 @@ func CustomHTTPErrorHandler(err error, c echo.Context) {
err = c.JSON(code, apimodels.APIError{
HTTPStatusCode: code,
Message: message,
RequestID: requestID,
})
}
if err != nil {
Expand Down

0 comments on commit 3548a73

Please sign in to comment.