I have this function:
var db *gorm.DB
func DeleteCategory(id uint) error {
var category Category
category.ID = id
result := db.Delete(&category)
fmt.Println("result.Error: ", result.Error)
return result.Error
}
This function should delete row in the database and it is, but when I call this function multiple time with the same id, I expect it to throw error message at the second call, but it always return nil:
result.Error: <nil>
*I'm using postgreSQL for the database
Trying to delete a row that doesn't exist is not considered an error by the SQL standard. If you need to return an error you should check the RowsAffected field.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With