How can I check for errors in CRUD operations using GORM?

I have tried the accepted answer, but it doesn't work, db.Error always return nil.

Just change something and it works, hope it helps somebody:

if err := db.Create(&Animal{Name: "Giraffe"}).Error; err != nil {
   // Create failed, do something e.g. return, panic etc.
   return 
}

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
}

Tags:

Go

Go Gorm