-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'main' into 45-be-implement-rate-limiting-for-api-endpoints
- Loading branch information
Showing
4 changed files
with
284 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
package server | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/go-playground/validator/v10" | ||
"github.com/labstack/echo/v4" | ||
"github.com/rs/zerolog/log" | ||
) | ||
|
||
type ErrorResponse struct { | ||
Status int `json:"status"` | ||
Message string `json:"message"` | ||
RequestID string `json:"request_id,omitempty"` | ||
Errors []string `json:"errors,omitempty"` | ||
} | ||
|
||
func globalErrorHandler(err error, c echo.Context) { | ||
req := c.Request() | ||
requestID := req.Header.Get(echo.HeaderXRequestID) | ||
|
||
// default error response | ||
status := http.StatusInternalServerError | ||
message := "internal server error" | ||
var validationErrors []string | ||
|
||
// handle different error types | ||
switch e := err.(type) { | ||
case *echo.HTTPError: | ||
status = e.Code | ||
message = e.Message.(string) | ||
|
||
case validator.ValidationErrors: | ||
// handle validation errors specially | ||
status = http.StatusBadRequest | ||
message = "validation failed" | ||
validationErrors = make([]string, len(e)) | ||
for i, err := range e { | ||
validationErrors[i] = err.Error() | ||
} | ||
|
||
case error: | ||
message = e.Error() | ||
} | ||
|
||
// log with more context | ||
logger := log.Error() | ||
if status < 500 { | ||
logger = log.Warn() | ||
} | ||
|
||
logger. | ||
Err(err). | ||
Str("request_id", requestID). | ||
Str("method", req.Method). | ||
Str("path", req.URL.Path). | ||
Int("status", status). | ||
Str("user_agent", req.UserAgent()). | ||
Msg("request error") | ||
|
||
// return json response | ||
if !c.Response().Committed { | ||
response := ErrorResponse{ | ||
Status: status, | ||
Message: message, | ||
RequestID: requestID, | ||
} | ||
if len(validationErrors) > 0 { | ||
response.Errors = validationErrors | ||
} | ||
|
||
if err := c.JSON(status, response); err != nil { | ||
log.Error(). | ||
Err(err). | ||
Str("request_id", requestID). | ||
Msg("failed to send error response") | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
package server | ||
|
||
import ( | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/go-playground/validator/v10" | ||
"github.com/labstack/echo/v4" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestGlobalErrorHandler(t *testing.T) { | ||
// setup | ||
e := echo.New() | ||
e.HTTPErrorHandler = globalErrorHandler | ||
|
||
// test cases | ||
tests := []struct { | ||
name string | ||
handler echo.HandlerFunc | ||
expectedStatus int | ||
expectedBody string | ||
}{ | ||
{ | ||
name: "http error", | ||
handler: func(c echo.Context) error { | ||
return echo.NewHTTPError(http.StatusBadRequest, "bad request") | ||
}, | ||
expectedStatus: http.StatusBadRequest, | ||
expectedBody: `{"status":400,"message":"bad request"}`, | ||
}, | ||
{ | ||
name: "generic error", | ||
handler: func(c echo.Context) error { | ||
return echo.NewHTTPError(http.StatusInternalServerError, "something went wrong") | ||
}, | ||
expectedStatus: http.StatusInternalServerError, | ||
expectedBody: `{"status":500,"message":"something went wrong"}`, | ||
}, | ||
{ | ||
name: "validation error", | ||
handler: func(c echo.Context) error { | ||
type TestStruct struct { | ||
Email string `validate:"required,email"` | ||
Age int `validate:"required,gt=0"` | ||
} | ||
|
||
v := validator.New() | ||
err := v.Struct(TestStruct{ | ||
Email: "invalid-email", | ||
Age: -1, | ||
}) | ||
|
||
return err | ||
}, | ||
expectedStatus: http.StatusBadRequest, | ||
expectedBody: `{ | ||
"status": 400, | ||
"message": "validation failed", | ||
"errors": [ | ||
"Key: 'TestStruct.Email' Error:Field validation for 'Email' failed on the 'email' tag", | ||
"Key: 'TestStruct.Age' Error:Field validation for 'Age' failed on the 'gt' tag" | ||
] | ||
}`, | ||
}, | ||
{ | ||
name: "with request id", | ||
handler: func(c echo.Context) error { | ||
c.Request().Header.Set(echo.HeaderXRequestID, "test-123") | ||
return echo.NewHTTPError(http.StatusBadRequest, "bad request") | ||
}, | ||
expectedStatus: http.StatusBadRequest, | ||
expectedBody: `{"status":400,"message":"bad request","request_id":"test-123"}`, | ||
}, | ||
} | ||
|
||
// run tests | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
req := httptest.NewRequest(http.MethodGet, "/", nil) | ||
rec := httptest.NewRecorder() | ||
c := e.NewContext(req, rec) | ||
|
||
err := tt.handler(c) | ||
if err != nil { | ||
e.HTTPErrorHandler(err, c) | ||
} | ||
|
||
assert.Equal(t, tt.expectedStatus, rec.Code) | ||
assert.JSONEq(t, tt.expectedBody, rec.Body.String()) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters