You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.0 KiB

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