duanjianxi8439 2015-05-20 22:47
浏览 178
已采纳

如何使用GORM检查CRUD操作中的错误?

The official documentation for GORM demonstrates a way in which one can test for the existence of a record, i.e.:

user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()}

// returns true if record hasn’t been saved (primary key `Id` is blank)
db.NewRecord(user) // => true

db.Create(&user)

// will return false after `user` created
db.NewRecord(user) // => false

This can be used to test indirectly for errors in record creation but reports no useful information in the event of a failure.

Having checked the source code for db.Create, there seems to be some sort of stack-frame inspection that checks for errors before proceeding, meaning that transactional errors will fail silently:

func Create(scope *Scope) {
    defer scope.Trace(NowFunc())

    if !scope.HasError() {
        // actually perform the transaction
    }
}
  • Is this a bug, or am I missing something?
  • How can/should I be informed of a failed transaction?
  • Where can I get useful debugging information?
  • 写回答

2条回答 默认 最新

  • dsaaqdz6223 2015-05-21 06:03
    关注

    DB.Create() returns a new (cloned) gorm.DB which is a struct and has a field Error:

    type DB struct {
        Value        interface{}
        Error        error
        RowsAffected int64
        // contains filtered or unexported fields
    }
    

    You can store the returned *gorm.DB value and check its DB.Error field like this:

    if dbc := db.Create(&user); dbc.Error != nil {
        // Create failed, do something e.g. return, panic etc.
        return
    }
    

    If you don't need anything else from the returned gorm.DB, you can directly check its Error field:

    if db.Create(&user).Error != nil {
        // Create failed, do something e.g. return, panic etc.
        return
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题