4 ms·
Regarding error context: I'd advocate simple error-chaining using a linked list. If a function fails, it returns an error wrapping the underlying error as the c
by davekeck 10y ago
Regarding error context: I'd advocate simple error-chaining using a linked list. If a function fails, it returns an error wrapping the underlying error as the cause, and so on up the stack. The top of the stack can inspect or print the error chain ("A failed because B failed because ..."), or pinpoint the error that was the root cause.
I would love for Go to include something like this:
type Error struct {
Description string
Cause error
}
func NewError(cause error, descriptionFmt string, args ...interface{}) error {
return Error{
Description: fmt.Sprintf(descriptionFmt, args...),
Cause: cause,
}
}
func (me Error) Error() string {
if me.Cause == nil {
return me.Description
}
return fmt.Sprintf("%v: %v", me.Description, me.Cause.Error())
}
func RootCause(err error) error {
if err, ok := err.(Error); ok && err.Cause != nil {
return RootCause(err.Cause)
}
return err
}
- tptacek 10y agoMany Go error libraries exist mostly to provide this kind of functionality.
- bjacokes 10y agoCheck out https://github.com/pkg/errors https://github.com/pkg/errors
- bmurphy1976 10y agoGreat library.
- rogpeppe1 10y agoor gopkg.in/errgo.v1 which is a bit more opinionated about error causes.