errors

package module
v0.0.0-...-d79ce87 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2021 License: MIT Imports: 6 Imported by: 7

README

errors pkg

Package errors is an advanced error handling library that can be used to propagate errors across boundaries, such as gRPC, and HTTP.

violations := []*errors.FieldViolation{
  {
    Field: "firstname",
    Description: "Field required",
  },
  {
    Field: "locality",
    Description: "Field required",
  },
}
err := errors.Bad(violations...)

Failure types

  • PermissionFailure
  • AuthenticationFailure
  • MissingFailure
  • BadRequest
  • PreconditionFailure
  • ConflictFailure
  • AvailabilityFailure
  • QuotaFailure

Wrapping

Just like with pkg/errors library, it is possible to wrap errors and thus keep the root cause of a failure to simplify debugging.

_, err := os.Stat(path)
if os.IsNotExist(err) {
  return errors.WithNotFound(err)
}

// Carry on...

i18n

TODO

Across the wire

gRPC
func (s *grpcServer) Denied(ctx context.Context, req *Request) (*Response, error) {
  return nil, grpcerrors.Pack(errors.PermissionDenied).Err()
}

This will return a 7 - codes.PermissionDenied status.

HTTP
http.HandleFunc("/precondition", func(w http.ResponseWriter, r *http.Request) {
  err := errors.FailedPrecondition(&errors.PreconditionViolation{
    Type: "TOS",
    Subject: "foo.app",
    Description: "Terms of service not accepted",
  })
  httperrors.Marshal(r, w, err)
})
log.Fatal(http.ListenAndServe(":8080", nil))

This will return a 412 - http.StatusPreconditionFailed status with the following payload (assuming the request expects a JSON response):

{
  "error": {
    "message": "1 preconditions failed",
    "details": [
      {
        "type": "TOS",
        "subject": "foo.app",
        "description": "Terms of service not accepted"
      }
    ]
  }
}

github.com/pkg/errors

This package wraps calls to the widely used pkg/errors library to simplify the import.

TODO

  • Localised messages
  • Unpack HTTP errors
  • Custom HTTP encoder/decoder

errors

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// PermissionDenied indicates the caller does not have permission to
	// execute the specified operation. It must not be used for rejections
	// caused by exhausting some resource (use ResourceExhausted
	// instead for those errors). It must not be
	// used if the caller cannot be identified (use Unauthenticated
	// instead for those errors).
	PermissionDenied error = &PermissionFailure{}

	// Unauthenticated indicates the request does not have valid
	// authentication credentials for the operation.
	Unauthenticated error = &AuthenticationFailure{}

	// NotFound means some requested entity (e.g., file or directory) was
	// not found.
	NotFound error = &MissingFailure{}
)

Functions

func Aborted

func Aborted(violations ...*ConflictViolation) error

Aborted indicates the operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc.

See litmus test above for deciding between FailedPrecondition, Aborted, and Unavailable.

func As

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

As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. As returns false if err is nil.

func Bad

func Bad(violations ...*FieldViolation) error

Bad indicates client specified an invalid argument. Note that this differs from FailedPrecondition. It indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).

func Cause

func Cause(err error) error

Cause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:

type causer interface {
       Cause() error
}

If the error does not implement Cause, the original error will be returned. If the error is nil, nil will be returned without further investigation.

func Errorf

func Errorf(format string, args ...interface{}) error

Errorf formats according to a format specifier and returns the string as a value that satisfies error. Errorf also records the stack trace at the point it was called.

func FailedPrecondition

func FailedPrecondition(violations ...*PreconditionViolation) error

FailedPrecondition indicates operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to a non-directory, etc.

A litmus test that may help a service implementor in deciding between FailedPrecondition, Aborted, and Unavailable:

(a) Use Unavailable if the client can retry just the failing call.
(b) Use Aborted if the client should retry at a higher-level
    (e.g., restarting a read-modify-write sequence).
(c) Use FailedPrecondition if the client should not retry until
    the system state has been explicitly fixed. E.g., if an "rmdir"
    fails because the directory is non-empty, FailedPrecondition
    should be returned since the client should not retry unless
    they have first fixed up the directory by deleting files from it.
(d) Use FailedPrecondition if the client performs conditional
    REST Get/Update/Delete on a resource and the resource on the
    server does not match the condition. E.g., conflicting
    read-modify-write on the same resource.

func Is

func Is(err error, target error) bool

Is reports whether any error in err's chain matches target.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

func IsAborted

func IsAborted(err error) bool

func IsBad

func IsBad(err error) bool

func IsFailedPrecondition

func IsFailedPrecondition(err error) bool

func IsNotFound

func IsNotFound(err error) bool

func IsPermissionDenied

func IsPermissionDenied(err error) bool

func IsResourceExhausted

func IsResourceExhausted(err error) bool

func IsUnauthenticated

func IsUnauthenticated(err error) bool

func IsUnavailable

func IsUnavailable(err error) bool

func New

func New(message string) error

New returns an error with the supplied message. New also records the stack trace at the point it was called.

func ResourceExhausted

func ResourceExhausted(violations ...*QuotaViolation) error

ResourceExhausted indicates some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.

func Unavailable

func Unavailable(retryDelay time.Duration) error

Unavailable indicates the service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff.

See litmus test above for deciding between FailedPrecondition, Aborted, and Unavailable.

func Unwrap

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

func WithAborted

func WithAborted(parent error, violations ...*ConflictViolation) error

WithAborted wraps `parent` with a `ConflictFailure`

func WithBad

func WithBad(parent error, violations ...*FieldViolation) error

WithBad wraps `parent` with a `BadRequest`

func WithFailedPrecondition

func WithFailedPrecondition(parent error, violations ...*PreconditionViolation) error

WithFailedPrecondition wraps `parent` with a `PreconditionFailure`

func WithMessage

func WithMessage(err error, message string) error

WithMessage annotates err with a new message. If err is nil, WithMessage returns nil.

func WithNotFound

func WithNotFound(parent error) error

WithNotFound wraps `parent` with a `MissingFailure`

func WithPermissionDenied

func WithPermissionDenied(parent error) error

WithPermissionDenied wraps `parent` with a `PermissionFailure`

func WithResourceExhausted

func WithResourceExhausted(parent error, violations ...*QuotaViolation) error

WithResourceExhausted wraps `parent` with a `QuotaFailure`

func WithStack

func WithStack(err error) error

WithStack annotates err with a stack trace at the point WithStack was called. If err is nil, WithStack returns nil.

func WithUnauthenticated

func WithUnauthenticated(parent error) error

WithUnauthenticated wraps `parent` with an `AuthenticationFailure`

func WithUnavailable

func WithUnavailable(parent error, retryDelay time.Duration) error

WithUnavailable wraps `parent` with an `AvailabilityFailure`

func Wrap

func Wrap(err error, message string) error

Wrap returns an error annotating err with a stack trace at the point Wrap is called, and the supplied message. If err is nil, Wrap returns nil.

func Wrapf

func Wrapf(err error, format string, args ...interface{}) error

Wrapf returns an error annotating err with a stack trace at the point Wrapf is call, and the format specifier. If err is nil, Wrapf returns nil.

Types

type AuthenticationFailure

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

func (*AuthenticationFailure) Error

func (e *AuthenticationFailure) Error() string

type AvailabilityFailure

type AvailabilityFailure struct {
	RetryInfo RetryInfo
	// contains filtered or unexported fields
}

func (*AvailabilityFailure) Error

func (e *AvailabilityFailure) Error() string

type BadRequest

type BadRequest struct {

	// Describes all violations in a client request.
	Violations []*FieldViolation
	// contains filtered or unexported fields
}

Describes violations in a client request. This error type focuses on the syntactic aspects of the request.

func (*BadRequest) Error

func (e *BadRequest) Error() string

type ConflictFailure

type ConflictFailure struct {

	// Describes all violations in a client request.
	Violations []*ConflictViolation
	// contains filtered or unexported fields
}

Describes violations in a client request. This error type focuses on the syntactic aspects of the request.

func (*ConflictFailure) Error

func (e *ConflictFailure) Error() string

type ConflictViolation

type ConflictViolation struct {
	// resource on which the conflict occurred.
	// For example, "user:<uuid>" or "billing/invoice:<uuid>".
	Resource string
	// A description of why the request element is bad.
	Description string
}

func (*ConflictViolation) String

func (v *ConflictViolation) String() string

type FieldViolation

type FieldViolation struct {
	// A path leading to a field in the request body. The value will be a
	// sequence of dot-separated identifiers that identify a protocol buffer
	// field. E.g., "field_violations.field" would identify this field.
	Field string
	// A description of why the request element is bad.
	Description string
}

A message type used to describe a single bad request field.

func (*FieldViolation) String

func (v *FieldViolation) String() string

type LocalisedMessage

type LocalisedMessage struct {
	// The locale used following the specification defined at
	// http://www.rfc-editor.org/rfc/bcp/bcp47.txt.
	// Examples are: "en-US", "fr-CH", "es-MX"
	Locale language.Tag
	// The localized error message in the above locale.
	Message string
}

Provides a localized error message that is safe to return to the user which can be attached to an RPC error.

type LocalisedString

type LocalisedString map[string]string

LocalisedString is a string that can contain multiple translations

The locale used following the specification defined at http://www.rfc-editor.org/rfc/bcp/bcp47.txt. Examples are: "en-US", "fr-CH", "es-MX"

func (LocalisedString) Match

func (s LocalisedString) Match(locales ...string) string

Match finds the best supported language based on the preferred list and the languages for which there exists translations

func (LocalisedString) String

func (s LocalisedString) String() string

type MissingFailure

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

func (*MissingFailure) Error

func (e *MissingFailure) Error() string

type PermissionFailure

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

func (*PermissionFailure) Error

func (e *PermissionFailure) Error() string

type PreconditionFailure

type PreconditionFailure struct {

	// Describes all precondition violations.
	Violations []*PreconditionViolation
	// contains filtered or unexported fields
}

Describes what preconditions have failed.

For example, if an RPC failed because it required the Terms of Service to be acknowledged, it could list the terms of service violation in the PreconditionFailure message.

func (*PreconditionFailure) Error

func (e *PreconditionFailure) Error() string

type PreconditionViolation

type PreconditionViolation struct {
	// The type of PreconditionFailure. We recommend using a service-specific
	// enum type to define the supported precondition violation types. For
	// example, "TOS" for "Terms of Service violation".
	Type string
	// The subject, relative to the type, that failed.
	// For example, "google.com/cloud" relative to the "TOS" type would
	// indicate which terms of service is being referenced.
	Subject string
	// A description of how the precondition failed. Developers can use this
	// description to understand how to fix the failure.
	//
	// For example: "Terms of service not accepted".
	Description string
}

A message type used to describe a single precondition failure.

func (*PreconditionViolation) String

func (v *PreconditionViolation) String() string

type QuotaFailure

type QuotaFailure struct {

	// Describes all quota violations.
	Violations []*QuotaViolation
	// contains filtered or unexported fields
}

Describes how a quota check failed.

For example if a daily limit was exceeded for the calling project, a service could respond with a QuotaFailure detail containing the project id and the description of the quota limit that was exceeded. If the calling project hasn't enabled the service in the developer console, then a service could respond with the project id and set `service_disabled` to true.

Also see RetryDetail and Help types for other details about handling a

func (*QuotaFailure) Error

func (e *QuotaFailure) Error() string

type QuotaViolation

type QuotaViolation struct {
	// The subject on which the quota check failed.
	// For example, "clientip:<ip address of client>" or "project:<Google
	// developer project id>".
	Subject string
	// A description of how the quota check failed. Clients can use this
	// description to find more about the quota configuration in the service's
	// public documentation, or find the relevant quota limit to adjust through
	// developer console.
	//
	// For example: "Service disabled" or "Daily Limit for read operations
	// exceeded".
	Description string
}

A message type used to describe a single quota violation. For example, a daily quota or a custom quota that was exceeded.

func (*QuotaViolation) String

func (v *QuotaViolation) String() string

type RetryInfo

type RetryInfo struct {
	// Clients should wait at least this long between retrying the same request.
	RetryDelay time.Duration
}

RetryInfo describes when the clients can retry a failed request. Clients could ignore the recommendation here or retry when this information is missing from error responses.

It's always recommended that clients should use exponential backoff when retrying.

Clients should wait until `retry_delay` amount of time has passed since receiving the error response before retrying. If retrying requests also fail, clients should use an exponential backoff scheme to gradually increase the delay between retries based on `retry_delay`, until either a maximum number of retires have been reached or a maximum retry delay cap has been reached.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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