Go simple error enums
Edit 1
Based on /r/golang/simple_error_enum
There are a few cases the previous way can go sideways so something like this would be more appropriate:
Definition
var (
ErrMissingValue = errors.New("missing value")
ErrWrongValue = errors.New("wrong value")
)
Usage
if err := f(); errors.Is(err, ErrMissingValue) {
// handle error
}
Original
Here is my take on having a consistent error API throughout the program.
From searching around, most of the ways described are really complicated in my opinion for doing this, so here is what I’m using:
Definition
type ErrorMessages struct {}
func (e ErrorMessages) MissingValue () string { return "missing value" }
func (e ErrorMessages) WrongValue () string { return "wrong value" }
Usage
if err.Error() == (ErrorMessages{}.MissingValue()) {
log.Println(ErrorMessages{}.MissingValue())
}