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...
}

Or

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

Dialect Translated Errors

If you would like to be able to use the dialect translated errors(like ErrDuplicatedKey), then enable the TranslateError flag when opening a db connection.

db, err := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{TranslateError: true})

ErrRecordNotFound

GORM returns ErrRecordNotFound when failed to find data with First, Last, Take (only when dialect translated errors are enabled). 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, gorm.ErrRecordNotFound)

Errors

Errors List

Platinum Sponsors

Gold Sponsors

Platinum Sponsors

Gold Sponsors