forked from mdouchement/standardfile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_error_handler.go
47 lines (41 loc) · 980 Bytes
/
http_error_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package middlewares
import (
"fmt"
"log"
"net/http"
"github.com/gofrs/uuid"
"github.com/labstack/echo/v4"
"github.com/cherya/standardfile/internal/sferror"
)
// HTTPErrorHandler is a middleware that formats rendered errors.
func HTTPErrorHandler(err error, c echo.Context) {
if !c.Response().Committed {
switch err := err.(type) {
case *echo.HTTPError:
log.Printf("Error [ECHO]: %s", err.Internal)
_ = c.JSON(err.Code, echo.Map{
"error": echo.Map{
"message": err.Message,
},
})
case *sferror.SFError:
status := sferror.StatusCode(err)
if status < 500 {
_ = c.JSON(status, err)
return
}
internal(err, c)
default:
internal(err, c)
}
}
}
func internal(err error, c echo.Context) {
id := uuid.Must(uuid.NewV4()).String()
log.Printf("Error [%s]: %s", id, err.Error())
_ = c.JSON(http.StatusInternalServerError, echo.Map{
"error": echo.Map{
"message": fmt.Sprintf("Unexpected error (id: %s)", id),
},
})
}