In Go, error handling is important.
You are encouraged to do error check after any Immediate Methods
Error Handling
Error handling in GORM is different than idiomatic Go code because of its chainable API, but still easy to implement.
If any error occurs, GORM will set *gorm.DB
‘s Error
field, which you can check like this:
if err := db.Where("name = ?", "jinzhu").First(&user).Error; err != nil { |
Or
if result := db.Where("name = ?", "jinzhu").First(&user); result.Error != nil { |
Errors
When processing data, it is common for multiple errors to occur. GORM provides an API to return all errors as a slice:
// If there are more than one error happened, `GetErrors` returns them as `[]error` |
RecordNotFound Error
GORM provides a shortcut to handle RecordNotFound
errors. If there are several errors, it will check if any of them is a RecordNotFound
error.
// Check if returns RecordNotFound error |