Created
March 26, 2020 06:20
-
-
Save thebevrishot/4ea7e17763b70019f43dbec5efa21024 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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