猿问

如何处理删除功能中的GORM错误?

我有这个功能:


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

}

这个函数应该删除数据库中的行,但是当我使用相同的id多次调用此函数时,我希望它在第二次调用时抛出消息,但它总是返回nil:*我正在使用数据库的postgreSQLerrorresult.Error:  <nil>


慕桂英4014372
浏览 126回答 1
1回答

皈依舞

尝试删除不存在的行不会被 SQL 标准视为错误。如果需要返回错误,则应检查“受影响的行”字段。func DeleteCategory(id uint) error {&nbsp; &nbsp; c := Category{ID:id}&nbsp; &nbsp; db := db.Delete(&c)&nbsp; &nbsp; if db.Error != nil {&nbsp; &nbsp; &nbsp; &nbsp; return db.Error&nbsp; &nbsp; } else if db.RowsAffected < 1 {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("row with id=%d cannot be deleted because it doesn't exist", id)&nbsp; &nbsp; }&nbsp; &nbsp; return nil}
随时随地看视频慕课网APP

相关分类

Go
我要回答