Errors Proposal
Goals
- To incorporate error codes in the new errors package. (Kind type defined below)
- Build on top of pre-existing widely used errors package github.com/pkg/errors to minimise breaking changes.
- Add a type called op based on Rob Pike’s package to hint the source of the error (under which function instead of using stack traces)
- Incorporate utility functions to unwrap to the source of the kind of error to have alternative decision making.
- Add support for marshalling and unmarshalling JSON request/responses.
- Add support for error monadic types.
Prior Art
https://github.com/upspin/upspin/blob/master/errors/errors.go (Author Rob Pike and B Fitzgerald)
https://commandcenter.blogspot.com/2017/12/error-handling-in-upspin.html
https://github.com/pkg/errors/blob/master/errors.go (Dave Cheney, probably one of the most widely used error packages but does not support structured and over the wire marshal and unmarshal of JSON types)
Prior Effort
https://github.com/etherlabsio/pkg/tree/master/errors
- Tried to fit all cases with a since error struct unlike github.com/pkg/errors which used composition of multiple struct types.
- Re-implementing a lot of what was already implemented in the packages mentioned above.
errors.WithStack(err) error
errors.WithMessage(err, string)
errors.WithMessagef(err, string, interface{}…)
errors.Wrap(err, string)
errors.Wrapf(err, string, interface{}…)
errors.WithOp(err, op)
errors.WithOpf(err, op, “”, interface{}…)
errors.WithKind(err, kind)
errors.WithKindf(err, kind, string, interface{}…)
errors.New(interface{}…)
Other Essential functions for unwrapping the errors:
errors.Cause(err) error : Returns an error at root, I.e Cause of the original error
errors.IsKind(err) bool : Tells whether an error is of a specific kind (If you wrap multiple errors)
Errors.IsMatch(err1, err2) bool : Are these two errors of the same kind, or are they the exact same pointer reference?
Kind int
Shared Enums
Internal // Internal error or inconsistency. This is the default if not provided.
Invalid // Invalid operation for this type of item.
Permission // Permission denied.
IO // External I/O error such as network failure.
AlreadyExist // Item already exists.
NotExist // Item does not exist.
// Generally the function name you want to wrap the op as
Op string
type jsonError {
Code int
Op string (optional)
Message string (optional)
}
// Error type returned as part of errors.New
type Error struct {
Kind Kind
Op Op
Cause error
}