Errors
import "errors"
Package errors implements functions to manipulate errors…
Package Index
There is only one function so far…
func New
func New(text string) error
New returns an error that formats as the given text.
Example Usage and Notes
- Return as error
Just call *New* with a short description of the error
f, err := os.Open(path)
if err != nil {
return nil, errors.New("open failed")
}
defer f.Close()
- Save as variable and reuse
Save the result struct in a variable and reuse it when needed
var OpenFailed = errors.New("open failed")
func ReadFile(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, OpenFailed
}
defer f.Close()
...
}
- A note about error strings from Go Code Review Guide
Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context.
That is, use
fmt.Errorf("something bad")
notfmt.Errorf("Something bad")
, so thatlog.Printf("Reading %s: %v", filename, err)
formats without a spurious capital letter mid-message.This does not apply to logging, which is implicitly line-oriented and not combined inside other messages.
- Different allocations should not be equal
…as they create 2 different error objects
errors.New("open failed") != errors.New("open failed")
Complete example
Internally New assigns the string to a struct that implements the Error() interface.
Questions
Why Error strings Should Not be capitalised in Go?
Answer: Because they are usually printed following other context.
Are 2 errors with the same message string the same?
Answer: No, because they have different allocations.
1. Alternative link ↩