Skip to content

Commit

Permalink
feat(httpserver): handle errors
Browse files Browse the repository at this point in the history
  • Loading branch information
rafael-piovesan committed May 23, 2022
1 parent a86e316 commit c10a916
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions pkg/httpserver/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package httpserver

import (
"errors"
"net/http"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/rafael-piovesan/go-rocket-ride/v2/pkg/config"
Expand All @@ -12,6 +15,44 @@ func New(cfg config.Config) *echo.Echo {

e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.HTTPErrorHandler = defaultHTTPErrorHandler

return e
}

func defaultHTTPErrorHandler(err error, c echo.Context) {
if c.Response().Committed {
return
}

c.Logger().Errorf("request error: %v", err)

code := http.StatusInternalServerError
message := any(http.StatusText(http.StatusInternalServerError))

var he *echo.HTTPError
if errors.As(err, &he) {
code = he.Code
message = he.Message
}

var be *echo.BindingError
if errors.As(err, &be) {
code = be.Code
message = be.Message
}

if m, ok := message.(string); ok {
message = map[string]any{"message": m}
}

// Send response
if c.Request().Method == http.MethodHead { // Issue #608
err = c.NoContent(code)
} else {
err = c.JSON(code, message)
}
if err != nil {
c.Logger().Errorf("failed writing error response: %v", err)
}
}

0 comments on commit c10a916

Please sign in to comment.