Last active
November 4, 2022 13:35
-
-
Save fogfish/061c0da30394eb0abbc0952764a2aaf9 to your computer and use it in GitHub Desktop.
Example of behaviour used for “Assert errors for behavior, not type”
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
// | |
// See the post: https://tech.fog.fish/2022/07/05/assert-golang-errors-for-behavior.html | |
// | |
// ErrorCodes provides a raw code originared by the failed package | |
type ErrorCode interface{ ErrorCode() string } | |
// ErrorType is the primary identifier (IRI) for the problem type, defined by the ontology | |
type ErrorType interface{ ErrorType() string } | |
// Ephemeral is short lifespan error | |
type Ephemeral interface{ Ephemeral() bool } | |
// Timeout of the operation | |
type Timeout interface{ Timeout() time.Duration } | |
// PreConditionFailed when effect conditions are evaluated to false by the entity (see Optimistic Locking) | |
type PreConditionFailed interface { PreConditionFailed() bool } | |
// Conflict when effect could not be fulfilled due to a conflict with the current state of the target resource (see Optimistic Locking). | |
type Conflict interface{ Conflict() bool } | |
// Gone when effect is aborted due to availability of target resource (see Optimistic Locking). | |
type Gone interface{ Gone() bool } | |
// NotFound when target resource is not available | |
type NotFound interface { NotFound() string } | |
// HTTP Problem Details (RFC 7807) | |
type ProblemDetails interface { | |
ErrorCode() string | |
ErrorType() string | |
ErrorInstance() string | |
ErrorTitle() string | |
ErrorDetail() string | |
} | |
// example of error wrapping function | |
func errSomeFailure(err error) error { | |
var name string | |
if pc, _, _, ok := runtime.Caller(1); ok { | |
name = runtime.FuncForPC(pc).Name() | |
} | |
return fmt.Errorf("[%s] something failed: %w", name, err) | |
} | |
// Example of recovery function | |
func recoverEphemeral(err errors) bool { | |
var e interface{ Ephemeral() bool } | |
ok := errors.As(err, &e) | |
return ok && e.Ephemeral() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment