jonhadfield
jonhadfield

Reputation: 165

Is it bad practice to reset an error in golang?

When parsing a string as text, I want any non-parseable string to result in a zero time and then carry on.

passwordLastUsed, err = time.Parse(time.RFC3339, record[lastUsed])
if err != nil {
    err = nil
    passwordLastUsed = time.Time{}
}

This code looks a bit messy and the 'ineffassign' linter returns this for the 'err = nil' statement:

warning: ineffectual assignment to err (ineffassign)

Is there a better way of handling this or should I just ignore the linter?

Upvotes: 8

Views: 18845

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79614

It's not bad practice to reset an error variable, if that's what you want to do.

It is bad practice to set variables that aren't used later--and that's what the warning is about.

There's probably never a reason to reset an error as you are doing, since after the if block err will always be nil.

It does make sense if you're only resetting in some cases. A common example:

result, err := db.Query(...)
if err == sql.ErrNoRows {
    err = nil // Ignore not-found rows
}
if err != nil {
    return err // But return all other errors
}

Upvotes: 17

Related Questions