Error Handling

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:

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


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


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:

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


Errors List