Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
jonhadfield Avatar asked Dec 22 '17 11:12

jonhadfield


People also ask

When should you panic Golang?

You can use panic for an unrecoverable error where the program is not able to continue its execution. You can also use panic if you want an error for a specific condition in your program.

Is error a type in Golang?

error is a built-in interface type in Go. An error variable represents any value that can describe itself as a string . The interface consists of a single function, Error() , that returns a string error message.


1 Answers

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
}
like image 196
Flimzy Avatar answered Sep 22 '22 14:09

Flimzy