arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/api/handlers.go
api/handlers.goRaw
 1package api
 2
 3import (
 4	"database/sql"
 5	"errors"
 6	"net/http"
 7
 8	"github.com/gin-gonic/gin"
 9	"github.com/hermeznetwork/hermez-node/db/historydb"
10	"github.com/hermeznetwork/hermez-node/log"
11	"github.com/hermeznetwork/tracerr"
12	"github.com/lib/pq"
13)
14
15const (
16	// maxLimit is the max permited items to be returned in paginated responses
17	maxLimit uint = 2049
18
19	// dfltOrder indicates how paginated endpoints are ordered if not specified
20	dfltOrder = historydb.OrderAsc
21
22	// dfltLimit indicates the limit of returned items in paginated responses if the query param limit is not provided
23	dfltLimit uint = 20
24
25	// 2^32 -1
26	maxUint32 = 4294967295
27
28	// 2^64 /2 -1
29	maxInt64 = 9223372036854775807
30
31	// Error for duplicated key
32	errDuplicatedKey = "Item already exists"
33
34	// Error for timeout due to SQL connection
35	errSQLTimeout = "The node is under heavy preasure, please try again later"
36
37	// Error message returned when context reaches timeout
38	errCtxTimeout = "context deadline exceeded"
39)
40
41var (
42	// ErrNillBidderAddr is used when a nil bidderAddr is received in the getCoordinator method
43	ErrNillBidderAddr = errors.New("biderAddr can not be nil")
44)
45
46func retSQLErr(err error, c *gin.Context) {
47	log.Warnw("HTTP API SQL request error", "err", err)
48	errMsg := tracerr.Unwrap(err).Error()
49	if errMsg == errCtxTimeout {
50		c.JSON(http.StatusServiceUnavailable, errorMsg{
51			Message: errSQLTimeout,
52		})
53	} else if sqlErr, ok := tracerr.Unwrap(err).(*pq.Error); ok {
54		// https://www.postgresql.org/docs/current/errcodes-appendix.html
55		if sqlErr.Code == "23505" {
56			c.JSON(http.StatusInternalServerError, errorMsg{
57				Message: errDuplicatedKey,
58			})
59		}
60	} else if tracerr.Unwrap(err) == sql.ErrNoRows {
61		c.JSON(http.StatusNotFound, errorMsg{
62			Message: err.Error(),
63		})
64	} else {
65		c.JSON(http.StatusInternalServerError, errorMsg{
66			Message: err.Error(),
67		})
68	}
69}
70
71func retBadReq(err error, c *gin.Context) {
72	log.Warnw("HTTP API Bad request error", "err", err)
73	c.JSON(http.StatusBadRequest, errorMsg{
74		Message: err.Error(),
75	})
76}