You have 3 main options:
based on the line, that is, to view the message. This, of course, is not bad, because if you later change one letter in the message, you need to rewrite the entire verification code so that I avoid it.
If the error messages can remain constant, simply create the errors as global variables, and then compare the received error with the known predetermined one.
For instance:
var ErrDB = errors.New("Database Error")
var ErrTimeout = errors.New("Timeout")
and then
if err := someFunc(); err != nil {
switch err {
case ErrDB:
case ErrTimeout:
}
}
- , - , .
:
const (
ErrDB = 1
ErrTimeout = 2
...
)
type MyError struct {
Code int
Message string
}
func (e MyError)Error() string {
return e.Message
}
func NewError(s string, code int) error {
return MyError{s,code}
}
, , - :
func someFunc() error {
if err := talkToDB(); err != nil {
return NewError(err.Error(), ErrDB)
}
return nil
}
:
if err := someFunc(); err != nil {
if me, ok := err.(MyError); ok {
switch me.Code {
case ErrDB:
....
}
}
}