-
Notifications
You must be signed in to change notification settings - Fork 11
/
error.go
69 lines (59 loc) 路 1.52 KB
/
error.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"context"
"net/http"
sentryecho "github.com/getsentry/sentry-go/echo"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
var (
errInvalidHashLength = errors.New("invalid hash: should be 32 bytes length")
errInvalidAddress = errors.New("invalid address")
errCancelRequest = "pq: canceling statement due to user request"
)
type NoRows interface {
IsNoRows(err error) bool
}
type Error struct {
Message string `json:"message"`
}
func badRequestError(c echo.Context, err error) error {
return c.JSON(http.StatusBadRequest, Error{
Message: err.Error(),
})
}
func internalServerError(c echo.Context, err error) error {
if hub := sentryecho.GetHubFromContext(c); hub != nil {
hub.CaptureMessage(err.Error())
}
return c.JSON(http.StatusInternalServerError, Error{
Message: err.Error(),
})
}
func handleError(c echo.Context, err error, noRows NoRows) error {
if err == nil {
return nil
}
if err.Error() == errCancelRequest {
return nil
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return c.JSON(http.StatusBadGateway, Error{
Message: err.Error(),
})
}
if noRows.IsNoRows(err) {
return c.NoContent(http.StatusNoContent)
}
if errors.Is(err, errInvalidAddress) {
return badRequestError(c, err)
}
return internalServerError(c, err)
}
func success(c echo.Context) error {
return c.JSON(http.StatusOK, echo.Map{
"message": "success",
})
}