Skip to content

Commit 304b417

Browse files
committed
adjust error message body style
1 parent c56b431 commit 304b417

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

internal/handlers/responseerr.go

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package handlers
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/labstack/echo/v4"
7+
)
8+
9+
type errorContent struct {
10+
Message interface{} `json:"message"`
11+
}
12+
type errorResponse struct {
13+
Error interface{} `json:"error"`
14+
}
15+
16+
func CustomHTTPErrorHandler(err error, c echo.Context) {
17+
he, ok := err.(*echo.HTTPError)
18+
if ok {
19+
if he.Internal != nil {
20+
if herr, ok := he.Internal.(*echo.HTTPError); ok {
21+
he = herr
22+
}
23+
}
24+
} else {
25+
he = &echo.HTTPError{
26+
Code: http.StatusInternalServerError,
27+
Message: http.StatusText(http.StatusInternalServerError),
28+
}
29+
}
30+
31+
// Send response
32+
if !c.Response().Committed {
33+
if c.Request().Method == http.MethodHead { // Issue #608
34+
err = c.NoContent(he.Code)
35+
} else {
36+
err = c.JSON(he.Code, errorResponse{
37+
Error: errorContent{
38+
Message: he.Message,
39+
},
40+
})
41+
}
42+
if err != nil {
43+
c.Logger().Error(err)
44+
}
45+
}
46+
}

internal/server/server.go

+2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"log"
88
"sandbox-go-api-sqlboiler-rest-auth/internal/config"
99
"sandbox-go-api-sqlboiler-rest-auth/internal/cookie"
10+
"sandbox-go-api-sqlboiler-rest-auth/internal/handlers"
1011

1112
"github.com/labstack/echo/v4"
1213
"go.uber.org/zap"
@@ -17,6 +18,7 @@ func NewServer(cfg *config.Config, db *sql.DB, l *zap.Logger) *echo.Echo {
1718
e := echo.New()
1819
e.HideBanner = true
1920
e.Debug = cfg.IsDev
21+
e.HTTPErrorHandler = handlers.CustomHTTPErrorHandler
2022

2123
bindGlobalMiddlewares(e, cfg, l, db, sc)
2224
bindRoutes(e, cfg, l, db, sc)

0 commit comments

Comments
 (0)