V8023. It is possible that a wrong variable of the 'error' type is checked for 'nil'.
The analyzer has detected code where the wrong variable of the error type is checked for nil. Due to their frequent use and the similarity in the names of the error type variables, the risk of making a mistake when dealing with them increases.
The example:
func decodeUser(data []byte) (err error) {
var u map[string] any
if e := json.Unmarshal(data, &u); err != nil {
return e
}
....
}
The result of the json.Unmarshal(data, &u) call is assigned to the e variable. However, the condition checks the err named return value. So, the result of json.Unmarshal(data, &u) is not checked at all, and a different value affects the function's return value.
To fix this, check e in the if statement:
func decodeUser(data []byte) (err error) {
var u map[string] any
if e := json.Unmarshal(data, &u); e != nil {
return e
}
....
}
Another example:
func decodeUser(data []byte) error {
var u map[string] any
e := validatePayload(data)
if e != nil {
return e
}
err := json.Unmarshal(data, &u)
if e != nil {
e = err
}
....
}
The data parameter is checked via the validatePayload function before being used. If the data contains an error, the function stops executing. Otherwise, the result of the json.Unmarshal(data, &u) call is assigned to the err variable, and then e is checked again. If an error occurs while executing json.Unmarshal(data, &u), the information will not be overwritten.
To fix this, check err in the if statement:
func decodeUser(data []byte) error {
var u map[string]any
e := validatePayload(data)
if e != nil {
return e
}
err := json.Unmarshal(data, &u)
if err != nil {
e = err
}
....
}