errors

package
v0.11.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 8, 2022 License: MPL-2.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func As

func As(err error, target interface{}) bool

As is the equivalent of the std errors.As, and allows devs to only import this package for the capability.

func E added in v0.1.3

func E(ctx context.Context, opt ...Option) error

E creates a new Err with provided code and supports the options of:

* WithoutEvent - allows you to specify that an error event should not be emitted.

* WithOp() - allows you to specify an optional Op (operation).

* WithMsg() - allows you to specify an optional error msg, if the default msg for the error Code is not sufficient.

* WithWrap() - allows you to specify an error to wrap. If the wrapped error is a boundary domain error, the wrapped error code will be used as the returned error's code.

* WithCode() - allows you to specify an optional Code, this code will be prioritized over a code used from WithWrap().

func EDeprecated added in v0.5.0

func EDeprecated(opt ...Option) error

EDeprecated is the legacy version of E which does not create an event. Please refrain from using this. When all calls are moved from EDeprecated to E, please update ICU-1883

func Is

func Is(err, target error) bool

Is the equivalent of the std errors.Is, but allows Devs to only import this package for the capability.

func IsCheckConstraintError

func IsCheckConstraintError(err error) bool

IsCheckConstraintError returns a boolean indicating whether the error is known to report a check constraint violation.

func IsMissingTableError

func IsMissingTableError(err error) bool

IsMissingTableError returns a boolean indicating whether the error is known to report a undefined/missing table violation.

func IsNotFoundError added in v0.1.3

func IsNotFoundError(err error) bool

IsNotFoundError returns a boolean indicating whether the error is known to report a not found violation.

func IsNotNullError

func IsNotNullError(err error) bool

IsNotNullError returns a boolean indicating whether the error is known to report a not-null constraint violation.

func IsUniqueError

func IsUniqueError(err error) bool

IsUniqueError returns a boolean indicating whether the error is known to report a unique constraint violation.

func Match

func Match(t *Template, err error) bool

Match the template against the error. The error must be of type *Err, or wrap an error of type *Err, otherwise match will return false. Matches all non-empty fields of the template against the error.

func New

func New(ctx context.Context, c Code, op Op, msg string, opt ...Option) error

New creates a new Err with provided code, op and msg It supports the options of:

* WithWrap() - allows you to specify an error to wrap

func NewDeprecated added in v0.5.0

func NewDeprecated(c Code, op Op, msg string, opt ...Option) error

NewDeprecated is the legacy version of New which does not create an event. Please refrain from using this. When all calls are moved from NewDeprecated to New, please update ICU-1883

func ToPbErrors added in v0.7.0

func ToPbErrors(err *Err) *pberrors.Err

ToPbErrors will convert to an Err protobuf

func Wrap added in v0.1.3

func Wrap(ctx context.Context, e error, op Op, opt ...Option) error

Wrap creates a new Err from the provided err and op, preserving the code from the originating error. It supports the options of:

* WithMsg() - allows you to specify an optional error msg, if the default msg for the error Code is not sufficient.

func WrapDeprecated added in v0.5.0

func WrapDeprecated(e error, op Op, opt ...Option) error

WrapDeprecated is the legacy version of New which does not create an event. Please refrain from using this. When all calls are moved from WrapDeprecated to New, please update ICU-1884

Types

type Code

type Code uint32

Code specifies a code for the error.

const (
	Unknown Code = 0 // Unknown will be equal to a zero value for Codes

	// General function errors are reserved Codes 100-999
	InvalidParameter              Code = 100 // InvalidParameter represents an invalid parameter for an operation.
	InvalidAddress                Code = 101 // InvalidAddress represents an invalid host address for an operation
	InvalidPublicId               Code = 102 // InvalidPublicId represents an invalid public Id for an operation
	InvalidFieldMask              Code = 103 // InvalidFieldMask represents an invalid field mast for an operation
	EmptyFieldMask                Code = 104 // EmptyFieldMask represents an empty field mask for an operation
	KeyNotFound                   Code = 105 // KeyNotFound represents that a key/version was not found in the KMS
	TicketAlreadyRedeemed         Code = 106 // TicketAlreadyRedeemed represents that the ticket version has already been redeemed
	TicketNotFound                Code = 107 // TicketNotFound represents that the ticket was not found
	Io                            Code = 108 // Io represents that an io error occurred in an underlying call (i.e binary.Write)
	InvalidTimeStamp              Code = 109 // InvalidTimeStamp represents an invalid time stamp for an operation
	SessionNotFound               Code = 110 // SessionNotFound represents that the session was not found
	InvalidSessionState           Code = 111 // InvalidSessionState represents that the session was in an invalid state
	TokenMismatch                 Code = 112 // TokenMismatch represents that there was a token mismatch
	TooShort                      Code = 113 // TooShort represents an error that means the provided input is not meeting minimum length requirements
	AccountAlreadyAssociated      Code = 114 // AccountAlreadyAssociated represents an attempt to associate an account failed since it was already associated.
	InvalidJobRunState            Code = 115 // InvalidJobRunState represents that a JobRun was in an invalid state
	InvalidDynamicCredential      Code = 116 // InvalidDynamicCredential represents that a dynamic credential for a session was in an invalid state
	JobAlreadyRunning             Code = 117 // JobAlreadyRunning represents that a Job is already running when an attempt to run again was made
	SubtypeAlreadyRegistered      Code = 118 // SubtypeAlreadyRegistered represents that a value has already been registered in the subtype registry system.
	NoPathFound                        = 119 // NoPathFound represents an error when no path is found to a worker
	WorkerNotFound                     = 120 // WorkerNotFound represents an error when a worker is not found in the graph of downstream workers
	CycleFound                         = 121 // CycleFound represents an error when a cycle is found between a parent and child worker
	WorkerConnNotFound                 = 122 // WorkerConnNotFound represents an error when a connection to a worker is not found
	KmsWorkerUnsupportedOperation      = 123 // KmsWorkerUnsupportedOperation represents an error when a KMS worker is not supported for an operation

	AuthAttemptExpired Code = 198 // AuthAttemptExpired represents an expired authentication attempt
	AuthMethodInactive Code = 199 // AuthMethodInactive represents an error that means the auth method is not active.

	// PasswordTooShort results from attempting to set a password which is to short.
	PasswordTooShort Code = 200

	// PasswordUnsupportedConfiguration results from attempting to perform an
	// operation that sets a password configuration to an unsupported type.
	PasswordUnsupportedConfiguration Code = 201

	// PasswordInvalidConfiguration results from attempting to perform an
	// operation that sets a valid password configuration with invalid settings.
	PasswordInvalidConfiguration Code = 202

	// PasswordsEqual is returned from ChangePassword when the old and
	// new passwords are equal.
	PasswordsEqual Code = 203

	Encrypt Code = 300 // Encrypt represents an error occurred during the underlying encryption process
	Decrypt Code = 301 // Decrypt represents an error occurred during the underlying decryption process
	Encode  Code = 302 // Encode represents an error occurred during the underlying encoding/marshaling process
	Decode  Code = 303 // Decode represents an error occurred during the underlying decoding/unmarshaling process
	GenKey  Code = 304 // GenKey represents an error occurred during the underlying key generation process
	GenCert Code = 305 // GenCert represents an error occurred during the underlying certificate generation process

	// General system errors are reserved Codes 400-599 and align with http
	// client and server error codes
	Unauthorized Code = 401 // Unauthorized represents the operation is unauthorized
	Forbidden    Code = 403 // Forbidden represents the operation is forbidden
	Internal     Code = 500 // InternalError represents the system encountered an unexpected condition.

	// DB errors are reserved Codes from 1000-1999
	CheckConstraint      Code = 1000 // CheckConstraint represents a check constraint error
	NotNull              Code = 1001 // NotNull represents a value must not be null error
	NotUnique            Code = 1002 // NotUnique represents a value must be unique error
	NotSpecificIntegrity Code = 1003 // NotSpecificIntegrity represents an integrity error that has no specific domain error code
	MissingTable         Code = 1004 // MissingTable represents an undefined table error
	RecordNotFound       Code = 1100 // RecordNotFound represents that a record/row was not found matching the criteria
	MultipleRecords      Code = 1101 // MultipleRecords represents that multiple records/rows were found matching the criteria
	ColumnNotFound       Code = 1102 // ColumnNotFound represent that a column was not found in the underlying db
	MaxRetries           Code = 1103 // MaxRetries represent that a db Tx hit max retires allowed
	Exception            Code = 1104 // Exception represent that an underlying db exception was raised
	VersionMismatch      Code = 1105 // VersionMismatch represents the update version and the db version for an entry do not match.
	// GracefullyAborted means we intended to abort a transaction but the
	// enclosing function should not treat it as an error; we aborted for
	// reasons related to the state of the DDL and/or inputs (such as we're
	// already in the right state and don't want to end up writing oplogs).
	GracefullyAborted Code = 1106
	// UnexpectedRowsAffected indicates that an action expected to operate on a
	// specific number of records returned a different count, e.g. if you
	// expected to delete three items and only one was deleted.
	UnexpectedRowsAffected Code = 1107

	// Migration setup errors are codes 2000-2999
	MigrationIntegrity Code = 2000 // MigrationIntegrity represents an error with the generated migration related code
	MigrationLock      Code = 2001 // MigrationLock represents an error related to locking of the DB

	// External system errors are reserved codes 3000-3999
	Unavailable Code = 3000 // Unavailable represents that an external system is unavailable

	// Vault specific errors
	VaultTokenNotOrphan           Code = 3010 // VaultTokenNotOrphan represents an error for a Vault token that is not an orphan token
	VaultTokenNotPeriodic         Code = 3011 // VaultTokenNotPeriodic represents an error for a Vault token that is not a periodic token
	VaultTokenNotRenewable        Code = 3012 // VaultTokenNotRenewable represents an error for a Vault token that is not renewable
	VaultTokenMissingCapabilities Code = 3013 // VaultTokenMissingCapabilities represents an error for a Vault token that is missing capabilities
	VaultCredentialRequest        Code = 3014 // VaultCredentialRequest represents an error returned from Vault when retrieving a credential
	VaultEmptySecret              Code = 3015 // VaultEmptySecret represents a empty secret was returned from Vault without error
	VaultInvalidMappingOverride   Code = 3016 // VaultInvalidMappingOverride represents an error returned when a credential mapping is unknown or does not match a credential type
	VaultInvalidCredentialMapping Code = 3017 // VaultInvalidCredentialMapping represents an error returned when a Vault secret failed to be mapped to a specific credential type

	// OIDC authentication provided errors
	OidcProviderCallbackError Code = 4000 // OidcProviderCallbackError represents an error that is passed by the OIDC provider to the callback endpoint
)

func (Code) Info

func (c Code) Info() Info

Info will look up the Code's Info. If the Info is not found, it will return Info for an Unknown Code.

func (Code) String

func (c Code) String() string

String will return the Code's Info.Message

type Err

type Err struct {
	// Code is the error's code, which can be used to get the error's
	// errorCodeInfo, which contains the error's Kind and Message
	Code Code

	// Msg for the error
	Msg string

	// Op represents the operation raising/propagating an error and is optional.
	// Op should be formatted as "package.func" for functions, while methods should
	// include the receiver type in parentheses "package.(type).func"
	Op Op

	// Wrapped is the error which this Err wraps and will be nil if there's no
	// error to wrap.
	Wrapped error
}

Err provides the ability to specify a Msg, Op, Code and Wrapped error. We've chosen Err over Error for the identifier to support the easy embedding of Errs. Errs can be embedded without a conflict between the embedded Err and Err.Error().

func Convert

func Convert(e error) *Err

Convert will convert the error to a Boundary *Err (returning it as an error) and attempt to add a helpful error msg as well. If that's not possible, it will return nil

func FromPbErrors added in v0.7.0

func FromPbErrors(pbErr *pberrors.Err) *Err

FromPbErrors will convert from Err protobuf

func (*Err) Error

func (e *Err) Error() string

Error satisfies the error interface and returns a string representation of the Err

func (*Err) Info

func (e *Err) Info() Info

Info about the Err

func (*Err) Unwrap

func (e *Err) Unwrap() error

Unwrap implements the errors.Unwrap interface and allows callers to use the errors.Is() and errors.As() functions effectively for any wrapped errors.

type Info

type Info struct {
	// Kind specifies the kind of error (unknown, parameter, integrity, etc).
	Kind Kind

	// Message provides a default message for the error code
	Message string
}

Info contains details of the specific error code

type Kind

type Kind uint32

Kind specifies the kind of error (unknown, parameter, integrity, etc).

const (
	Other Kind = iota
	Parameter
	Integrity
	Search
	Password
	Transaction
	Encryption
	Encoding
	State
	External
	VaultToken
)

func (Kind) String

func (e Kind) String() string

type Op

type Op string

Op represents an operation (package.function). For example iam.CreateRole

type Option

type Option func(*Options)

Option - how Options are passed as arguments.

func WithCode added in v0.1.3

func WithCode(code Code) Option

WithCode provides an option to provide a code when creating a new error.

func WithMsg

func WithMsg(msg string, args ...any) Option

WithMsg provides an option to provide a message when creating a new error. If args are provided, the the msg string is used as a fmt specifier for the arguments and the resulting string is used as the msg.

func WithOp

func WithOp(op Op) Option

WithOp provides an option to provide the operation that's raising/propagating the error.

func WithWrap

func WithWrap(e error) Option

WithErrCode provides an option to provide an error to wrap when creating a new error.

func WithoutEvent added in v0.5.0

func WithoutEvent() Option

WithoutEvent provides an option to suppress the event when wrapping or creating a new error.

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options - how Options are represented.

func GetOpts

func GetOpts(opt ...Option) Options

GetOpts - iterate the inbound Options and return a struct.

type Template

type Template struct {
	Err       // Err embedded to support matching Errs
	Kind Kind // Kind allows explicit matching on a Template without a Code.
}

Template is useful constructing Match Err templates. Templates allow you to match Errs without specifying a Code. In other words, just Match using the Errs: Kind, Op, etc.

func T

func T(args ...interface{}) *Template

T creates a new Template for matching Errs. Invalid parameters are ignored. If more than is one parameter for a given type, only the last one is used.

func (*Template) Error

func (t *Template) Error() string

Error satisfies the error interface but we intentionally don't return anything of value, in an effort to stop users from substituting Templates in place of Errs, when creating domain errors.

func (*Template) Info

func (t *Template) Info() Info

Info about the Template, which is useful when matching a Template's Kind with an Err's Kind.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL