Handling Errors in GORM's Delete Function
When working with database deletions using GORM, it's crucial to consider how you want to handle non-existent rows. By default, GORM does not throw an error when trying to delete a non-existent row. Instead, the result.Error field remains nil.
To alter this behavior and return an error for non-existent rows, you need to inspect the RowsAffected field. Here's how you can modify your DeleteCategory function:
<code class="go">func DeleteCategory(id uint) error { c := Category{ID: id} db := db.Delete(&c) if db.Error != nil { return db.Error } else if db.RowsAffected < 1 { return fmt.Errorf("row with id=%d cannot be deleted because it doesn't exist", id) } return nil }</code>
In this modified function:
The above is the detailed content of How to Handle Non-Existent Rows in GORM\'s Delete Function?. For more information, please follow other related articles on the PHP Chinese website!