diff --git a/pkg/common/db/relation/mysql_init.go b/pkg/common/db/relation/mysql_init.go index 628c695a4..6fa697537 100644 --- a/pkg/common/db/relation/mysql_init.go +++ b/pkg/common/db/relation/mysql_init.go @@ -7,6 +7,7 @@ import ( "OpenIM/pkg/errs" "context" "fmt" + mysqlDriver "github.com/go-sql-driver/mysql" "gorm.io/driver/mysql" "strings" "time" @@ -65,9 +66,24 @@ func newMysqlGormDB() (*gorm.DB, error) { // gorm mysql func NewGormDB() (*gorm.DB, error) { specialerror.AddReplace(gorm.ErrRecordNotFound, errs.ErrRecordNotFound) + specialerror.AddErrHandler(replaceDuplicateKey) return newMysqlGormDB() } +func replaceDuplicateKey(err error) errs.CodeError { + if IsMysqlDuplicateKey(err) { + return errs.ErrDuplicateKey + } + return nil +} + +func IsMysqlDuplicateKey(err error) bool { + if mysqlErr, ok := err.(*mysqlDriver.MySQLError); ok { + return mysqlErr.Number == 1062 + } + return false +} + type Writer struct{} func (w Writer) Printf(format string, args ...interface{}) { diff --git a/pkg/errs/code.go b/pkg/errs/code.go index b8cad6ffc..965d1353d 100644 --- a/pkg/errs/code.go +++ b/pkg/errs/code.go @@ -40,6 +40,8 @@ const ( CallbackError = 80000 ) +const DuplicateKeyError = 12345 + // 账号错误码 const ( UserIDNotFoundError = 91001 //UserID不存在 或未注册 diff --git a/pkg/errs/predefine.go b/pkg/errs/predefine.go index d495fa183..e18cdf4eb 100644 --- a/pkg/errs/predefine.go +++ b/pkg/errs/predefine.go @@ -41,6 +41,7 @@ var ( ErrTokenNotExist = NewCodeError(TokenNotExistError, "TokenNotExistError") //在redis中不存在 ErrTokenDifferentPlatformID = NewCodeError(TokenDifferentPlatformIDError, "TokenDifferentPlatformIDError") ErrTokenDifferentUserID = NewCodeError(TokenDifferentUserIDError, "TokenDifferentUserIDError") + ErrDuplicateKey = NewCodeError(DuplicateKeyError, "DuplicateKeyError") ErrMessageHasReadDisable = NewCodeError(MessageHasReadDisable, "MessageHasReadDisable")