Question

I am trying to update a record in the database using the document's ID to identify it. If the update is successful, I expect an to get back the updated record and send it back via a REST API. If the update fails due to the record not being in the database (i.e. the ID was not found), I expect to get a gorm.ErrRecordNotFound

This is the code I am using to do the update.

func UpdateTodo(w http.ResponseWriter, r *http.Request) {
    var t models.Todo
    params := mux.Vars(r)
    todoId, err := strconv.ParseInt(params["todoId"], 10, 64)

    if err != nil {
        http.Error(w, fmt.Sprintf("Todo with ID = %s not found", params["todoId"]), http.StatusNotFound)
        return
    }

    err = decodeJSONBody(r, &t)

    if err != nil {
        http.Error(w, "Invalid input data. Try again.", http.StatusBadRequest)
        return
    }

    updates := map[string]interface{}{
        "complete": t.Complete,
    }

    if t.Task != "" {
        updates["task"] = t.Task
    }

    err = initializers.DB.Model(&t).Where("id = ?", todoId).Updates(updates).Error

    if err != nil {

        if errors.Is(err, gorm.ErrRecordNotFound) {
            http.Error(w, fmt.Sprintf("Todo with ID = %d not found", todoId), http.StatusNotFound)
            return
        }

        http.Error(w, "An error occurred. Try later", http.StatusInternalServerError)
        return
    }

    b, err := encodeJSONBody(t)

    if err != nil {
        http.Error(w, "An error occurred. Try later", http.StatusInternalServerError)
        return
    }

    _, err = w.Write(b)

    if err != nil {
        http.Error(w, "An error occurred. Try later", http.StatusInternalServerError)
        return
    }
}

I was expecting to get a gorm.ErrRecordNotFound but no error is being produced. Even if I make updates using an ID that is way out of range I am still getting back something. If I do make an update to a record that I know exists in the database, it is working but I'm not getting back the updated record on t. I thought this would be the case since I am passing &t to this. Am I doing something wrong with these updates? Please help.

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days