Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle GORM error at Delete function?

Tags:

go

go-gorm

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

like image 475
pranotobudi Avatar asked Sep 01 '26 03:09

pranotobudi


1 Answers

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
}
like image 137
mkopriva Avatar answered Sep 03 '26 22:09

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!