Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(web): Add a custom error handler to gokit #16

Merged
merged 1 commit into from
Feb 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
57 changes: 57 additions & 0 deletions web/error/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package error

import (
"net/http"

"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
)

func Handler(logger zerolog.Logger) echo.HTTPErrorHandler {
ll := logger.With().Str("middleware", "errorHandler").Logger()
return func(err error, c echo.Context) {
if c.Response().Committed {
return
}

ll.Err(err).
Str("requestID", c.Request().Header.Get(echo.HeaderXRequestID)).
Msg("request returned an error")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change 1 is here. Regardless of what the error is, it needs to be logged. The logger on line 54 would log the error that gets returned from c.JSON or c.NoContent.


he, ok := err.(*echo.HTTPError)
if ok {
if he.Internal != nil {
if herr, ok := he.Internal.(*echo.HTTPError); ok {
he = herr
}
}
} else {
he = &echo.HTTPError{
Code: http.StatusInternalServerError,
Message: http.StatusText(http.StatusInternalServerError),
}
}

// Issue #1426
code := he.Code
message := he.Message
if m, ok := he.Message.(string); ok {
if c.Echo().Debug {
message = echo.Map{"code": code, "message": m, "error": err.Error()}
} else {
message = echo.Map{"code": code, "message": m}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change 2 is here. The "code": code, was added to both messages.

See original: https://github.com/labstack/echo/blob/82a964c657e26b68998393d3e7291f1a474447f8/echo.go#L414-L416

}
}

// Send response
if c.Request().Method == http.MethodHead { // Issue #608
err = c.NoContent(he.Code)
} else {
err = c.JSON(code, message)
}
if err != nil {

c.Logger().Error(err)
}
}
}