From 28f026f6282d2509f6d154547e18e5b9f0fca6b5 Mon Sep 17 00:00:00 2001 From: arnaubennassar Date: Thu, 18 Feb 2021 15:55:13 +0100 Subject: [PATCH] Duplicated error when caused by meddler --- api/handlers.go | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/api/handlers.go b/api/handlers.go index 90ce3a7..0db395c 100644 --- a/api/handlers.go +++ b/api/handlers.go @@ -10,6 +10,7 @@ import ( "github.com/hermeznetwork/hermez-node/log" "github.com/hermeznetwork/tracerr" "github.com/lib/pq" + "github.com/russross/meddler" ) const ( @@ -46,24 +47,33 @@ var ( func retSQLErr(err error, c *gin.Context) { log.Warnw("HTTP API SQL request error", "err", err) errMsg := tracerr.Unwrap(err).Error() - if errMsg == errCtxTimeout { - c.JSON(http.StatusServiceUnavailable, errorMsg{ - Message: errSQLTimeout, - }) - } else if sqlErr, ok := tracerr.Unwrap(err).(*pq.Error); ok { + retDupKey := func(errCode pq.ErrorCode) { // https://www.postgresql.org/docs/current/errcodes-appendix.html - if sqlErr.Code == "23505" { + if errCode == "23505" { c.JSON(http.StatusInternalServerError, errorMsg{ Message: errDuplicatedKey, }) + } else { + c.JSON(http.StatusInternalServerError, errorMsg{ + Message: errMsg, + }) } + } + if errMsg == errCtxTimeout { + c.JSON(http.StatusServiceUnavailable, errorMsg{ + Message: errSQLTimeout, + }) + } else if sqlErr, ok := tracerr.Unwrap(err).(*pq.Error); ok { + retDupKey(sqlErr.Code) + } else if sqlErr, ok := meddler.DriverErr(tracerr.Unwrap(err)); ok { + retDupKey(sqlErr.(*pq.Error).Code) } else if tracerr.Unwrap(err) == sql.ErrNoRows { c.JSON(http.StatusNotFound, errorMsg{ - Message: err.Error(), + Message: errMsg, }) } else { c.JSON(http.StatusInternalServerError, errorMsg{ - Message: err.Error(), + Message: errMsg, }) } }