Skip to content

Instantly share code, notes, and snippets.

@thebevrishot
Created March 26, 2020 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebevrishot/4ea7e17763b70019f43dbec5efa21024 to your computer and use it in GitHub Desktop.
Save thebevrishot/4ea7e17763b70019f43dbec5efa21024 to your computer and use it in GitHub Desktop.
package errors
import "fmt"
type ErrCode uint64
const (
IOError ErrCode = 0x00
LogicError ErrCode = 0x01
)
func errorName(code ErrCode) string {
switch code {
case IOError:
return "IO_ERROR"
case LogicError:
return "LOGIC_ERROR"
default:
return "UNKNOWN"
}
}
type CustomErr struct {
code ErrCode
inner error
message string
// Context
}
func (e *CustomErr) Error() string {
if e.inner != nil {
return fmt.Sprintf("{\"type\": \"%s\",\"message\": \"%s\", \"inner\": %+v}", errorName(e.code), e.message, e.inner)
}
return fmt.Sprintf("{\"type\": \"%s\", \"message\": \"%s\"}", errorName(e.code), e.message)
}
func (e *CustomErr) Is(code ErrCode) bool {
return e.code == code
}
// Constructors
func err(c ErrCode, i error, m string) error {
return &CustomErr{code: c, inner: i, message: m}
}
func LogicErr(message string) error {
return LogicErrWithInner(message, nil)
}
func LogicErrWithInner(message string, inner error) error {
return err(LogicError, inner, message)
}
func IOErr(message string) error {
return IOErrWithInner(message, nil)
}
func IOErrWithInner(message string, inner error) error {
return err(IOError, inner, message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment