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
35var (
36	// ErrNillBidderAddr is used when a nil bidderAddr is received in the getCoordinator method
37	ErrNillBidderAddr = errors.New("biderAddr can not be nil")
38)
39
40func retSQLErr(err error, c *gin.Context) {
41	log.Warn("HTTP API SQL request error", "err", err)
42	if sqlErr, ok := tracerr.Unwrap(err).(*pq.Error); ok {
43		// https://www.postgresql.org/docs/current/errcodes-appendix.html
44		if sqlErr.Code == "23505" {
45			c.JSON(http.StatusInternalServerError, errorMsg{
46				Message: errDuplicatedKey,
47			})
48		}
49	}
50	if tracerr.Unwrap(err) == sql.ErrNoRows {
51		c.JSON(http.StatusNotFound, errorMsg{
52			Message: err.Error(),
53		})
54	} else {
55		c.JSON(http.StatusInternalServerError, errorMsg{
56			Message: err.Error(),
57		})
58	}
59}
60
61func retBadReq(err error, c *gin.Context) {
62	log.Warn("HTTP API Bad request error", "err", err)
63	c.JSON(http.StatusBadRequest, errorMsg{
64		Message: err.Error(),
65	})
66}