Skip to content

Commit

Permalink
Merge pull request #16 from suborbital/gabor/15-echo-error-handler
Browse files Browse the repository at this point in the history
feat(web): Add a custom error handler to gokit
  • Loading branch information
javorszky committed Feb 6, 2023
2 parents e4eace0 + 741676e commit 265d2bb
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions web/error/handler.go
@@ -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")

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}
}
}

// 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)
}
}
}

0 comments on commit 265d2bb

Please sign in to comment.