golang: Error Checking

There’s a problem with the error checking in this go function:

func GetObjectById(id int64) (o *Object, err error) {
    obj, err := dbmap.Get(Object{}, id)
    if obj == nil {
        return o, errors.New("Object: not found.")
    } else if err != nil {
        return o, err
    }

    return obj.(*Object), nil
}

The docs for gorp state that DbMap.Get will return “nil if no row is found”, so we’re watching for that condition and handling it appropriately.

The problem is that if DbMap.Get returns an error, the return value will still be nil, but because of the order priority in our if/else if clause, we’ll never get to the error check condition. This caught me off-guard yesterday (because of an unrelated database error).

Lesson learned: if a function returns an error, it’s probably best to check that first.

    obj, err := dbmap.Get(Object{}, id)
    // Check the error first!
    if err != nil {
        return o, err
    } else if obj == nil {
        return o, errors.New("Object: not found.")
    }