pranotobudi
pranotobudi

Reputation: 67

How to handle GORM error at Delete function?

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

Upvotes: 6

Views: 3726

Answers (1)

mkopriva
mkopriva

Reputation: 38303

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
}

Upvotes: 13

Related Questions