gorm error支持不够

Created on 2 Jan 2018  ·  6Comments  ·  Source: go-gorm/gorm

当Id重复时,gorm返回的error信息如下。 由于gorm定义的error没有Duplicate error, 所以我这边不好做进一步的业务逻辑。

(Error 1062: Duplicate entry '5a' for key 'task_id_idx')

但是gorm的error 设定的错误信息里,只有下面几个. 能否支持更多的mysql的error错误。

    // ErrRecordNotFound record not found error, happens when haven't find any matched data when looking up with a struct
    ErrRecordNotFound = errors.New("record not found")
    // ErrInvalidSQL invalid SQL error, happens when you passed invalid SQL
    ErrInvalidSQL = errors.New("invalid SQL")
    // ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
    ErrInvalidTransaction = errors.New("no valid transaction")
    // ErrCantStartTransaction can't start transaction when you are trying to start one with `Begin`
    ErrCantStartTransaction = errors.New("can't start transaction")
    // ErrUnaddressable unaddressable value
    ErrUnaddressable = errors.New("using unaddressable value")

Most helpful comment

handle duplicate key error.

    err = db.Create(&entry).Error
    mysqlErr, ok := err.(*mysql.MySQLError)
    if ok {
        if mysqlErr.Number == 1062 {
                         // solve the duplicate key error.
            fmt.Printf("duplicate key, error: %s", mysqlErr)
        }
    }

Gorm is ORM (Object Relational Mapping).
SQL driver interact with mysql server.
The error message is returned by sql driver.

All 6 comments

你还好,我连错误怎么处理的入口都找不到 :-(

the error is return the SQL driver, not GORM.

@free1139 it is explained in doc.

I think it' best for gorm to catch the duplicate key error, it will be convenient for the user

I also met this problem, how should I deal with it. @rfyiamcool

handle duplicate key error.

    err = db.Create(&entry).Error
    mysqlErr, ok := err.(*mysql.MySQLError)
    if ok {
        if mysqlErr.Number == 1062 {
                         // solve the duplicate key error.
            fmt.Printf("duplicate key, error: %s", mysqlErr)
        }
    }

Gorm is ORM (Object Relational Mapping).
SQL driver interact with mysql server.
The error message is returned by sql driver.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

koalacxr picture koalacxr  ·  3Comments

leebrooks0 picture leebrooks0  ·  3Comments

corvinusy picture corvinusy  ·  3Comments

izouxv picture izouxv  ·  3Comments

kumarsiva07 picture kumarsiva07  ·  3Comments