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