Simplify Error Construction
ID |
go.simplify_error_construction |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Go |
Tags |
best-practice, code-style |
Description
Reports errors.New(fmt.Sprintf(…)), the round-about way of building a formatted error.
The standard library provides fmt.Errorf, which formats and wraps the message in a single call.
Rationale
fmt.Errorf(format, args…) does exactly what the nested errors.New(fmt.Sprintf(…)) pair
does, with one fewer call and one fewer allocation. fmt.Errorf also supports the %w verb for
error wrapping, so preferring it keeps the door open to proper error chains.
// Bad
return errors.New(fmt.Sprintf("n=%d below zero", n))
// Good
return fmt.Errorf("n=%d below zero", n)