When working with a database, it's crucial to handle potential errors gracefully. In GORM, the Delete function, intended to remove an entity from the database, presents a specific issue where multiple calls with the same identifier don't trigger an error.
By default, GORM doesn't consider attempting to delete a non-existent row in the database as an error. Therefore, the Delete function simply returns nil in such cases, even if it fails to remove the entity.
This behavior stems from the fact that GORM follows the SQL standard, which doesn't define deleting a non-existent row as an error. As a result, GORM doesn't inherently throw an error when you try to delete a non-existent row.
If you need to return an error when attempting to delete a non-existent row, you have to manually check the RowsAffected field of the Delete function's result. Here's how you can modify your code:
<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 code:
The above is the detailed content of How to Ensure Error Handling During Entity Deletion in GORM when Rows are Not Found?. For more information, please follow other related articles on the PHP Chinese website!