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.

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