{"id":1246,"hash":"54a08896f5f551004876a808c9d03c7f9b63bf793a7fc69924afaeda861849bb","pattern":"How can I check for errors in CRUD operations using GORM?","full_message":"The official documentation for GORM demonstrates a way in which one can test for the existence of a record, i.e.:\n\nuser := User{Name: \"Jinzhu\", Age: 18, Birthday: time.Now()}\n\n// returns true if record hasn’t been saved (primary key `Id` is blank)\ndb.NewRecord(user) // => true\n\ndb.Create(&user)\n\n// will return false after `user` created\ndb.NewRecord(user) // => false\n\nThis can be used to test indirectly for errors in record creation but reports no useful information in the event of a failure.\n\nHaving 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:\n\nfunc Create(scope *Scope) {\n    defer scope.Trace(NowFunc())\n\n    if !scope.HasError() {\n        // actually perform the transaction\n    }\n}\n\nIs this a bug, or am I missing something?\nHow can/should I be informed of a failed transaction?\nWhere can I get useful debugging information?","ecosystem":"go","package_name":"go-gorm","package_version":null,"solution":"DB.Create() returns a new (cloned) gorm.DB which is a struct and has a field Error:\n\ntype DB struct {\n    Value        interface{}\n    Error        error\n    RowsAffected int64\n    // contains filtered or unexported fields\n}\n\nYou can store the returned *gorm.DB value and check its DB.Error field like this:\n\nif dbc := db.Create(&user); dbc.Error != nil {\n    // Create failed, do something e.g. return, panic etc.\n    return\n}\n\nIf you don't need anything else from the returned gorm.DB, you can directly check its Error field:\n\nif db.Create(&user).Error != nil {\n    // Create failed, do something e.g. return, panic etc.\n    return\n}","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/30361671/how-can-i-check-for-errors-in-crud-operations-using-gorm","votes":25,"created_at":"2026-04-19T04:52:42.958043+00:00","updated_at":"2026-04-19T04:52:42.958043+00:00"}