When utilizing GORM's Delete function to remove rows from a database, it's important to handle potential errors. While the provided function successfully deletes the specified row, it may not always return an error when attempting to delete a non-existent row, leading to unexpected behavior. To resolve this, we need to verify the status of the deletion operation by checking the RowsAffected field.
<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 revised function, we check for both database-related errors and the absence of affected rows. If no rows are affected, it means the row with the specified ID does not exist, and an error is returned to indicate this. This approach provides a more accurate and consistent handling of deletion operations, ensuring that the desired behavior is maintained even in the case of non-existent rows.
The above is the detailed content of How to Handle Errors When Deleting Rows with GORM\'s Delete Function?. For more information, please follow other related articles on the PHP Chinese website!