In Go, error handling is important.

You are encouraged to do error check after any Finisher Methods

Error Handling

Error handling in GORM is different than idiomatic Go code because of its chainable API.

If any error occurs, GORM will set *gorm.DB‘s Error field, you need to check it like this:

  1. if err := db.Where("name = ?", "jinzhu").First(&user).Error; err != nil {
  2. // error handling...
  3. }

Or

  1. if result := db.Where("name = ?", "jinzhu").First(&user); result.Error != nil {
  2. // error handling...
  3. }

ErrRecordNotFound

GORM returns ErrRecordNotFound when failed to find data with First, Last, Take, if there are several errors happened, you can check the ErrRecordNotFound error with errors.Is, for example:

  1. // Check if returns RecordNotFound error
  2. err := db.First(&user, 100).Error
  3. errors.Is(err, gorm.ErrRecordNotFound)

Errors

Errors List