erraux

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2023 License: Apache-2.0 Imports: 7 Imported by: 4

Documentation

Overview

Package erraux provides auxiliary functionality for marshaling and returning errors over HTTP.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsTemporary

func IsTemporary(err error) bool

IsTemporary tests if the given error is marked as a temporary error. This method returns true if the given error or what the error wraps exposes a Temporary() bool method that returns true.

This function uses errors.As to traverse the error wrappers.

See: https://pkg.go.dev/net/#Error

Types

type Causer added in v0.2.1

type Causer interface {
	Cause() string
}

Causer can be implemented by errors to produce a cause, which corresponds to the JSON field of the same name. An error may choose to do this because the Error() method might be targeted at logs or other plain text output, while Cause() is specifically for a JSON representation.

type Encoder

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

Encoder defines a ruleset for writing golang errors to HTTP representations. The zero value is a valid encoder that will simply encode all errors with a default JSON representation.

This type does not honor json.Marshaler. Each error being allowed to marshal itself as needed leads to many different error representations with no guarantee of being consistent. Rather, this type enforces a standard JSON representation and supports optional interfaces that custom errors may implement that can tailor parts of the HTTP response.

func (Encoder) Add

func (e Encoder) Add(rules ...EncoderRule) Encoder

Add defines rules created with either Is or As.

func (Encoder) Body added in v0.2.1

func (e Encoder) Body(v bool) Encoder

Body controls whether HTTP response bodies are rendered for any rules added afterward. By default, an Encoder will render a JSON payload for each error.

Invoking this method only affects subsequent calls up to the next invocation:

Encoder{}.
  Body(false).
    // these errors will be rendered without a body
    Is(ErrSomething).
    As((*SomeError)(nil).
  Body(true).
    // this error will be rendered with a body
    As((*MyError)(nil)) // this will be rendered with a body

func (Encoder) Encode

func (e Encoder) Encode(ctx context.Context, err error, rw http.ResponseWriter)

Encode is a gokit-style error encoder. Each rule in this encoder is tried in the order they were added via Add. If no rule can handle the error, a default JSON representation is used.

The minimal JSON error representation has two fields: code and cause. The code is the HTTP status code, and will be the same as what was passed to WriteHeader. The cause field is the value of Error(). For example:

{"code": 404, "cause": "resource not found"}
{"code": 500, "cause": "parsing error"}

Beyond that, errors may implement StatusCoder, Headerer, and ErrorFielder to tailor the HTTP representation. Any status code set on the rules will override any value the error supplies. For example:

type MyError struct{}
func (e *MyError) StatusCode() int { return 504 }
func (e *MyError) Error() string { "my error" }

// this will override MyError.StatusCode
e := erraux.Encoder{}.Add(
    erraux.As((*MyError)(nil)).StatusCode(500),
)

By contrast, an headers or fields set on the rule will be appended to whatever the error defines at runtime.

This method may be used with go-kit's transport/http package as an ErrorEncoder.

type EncoderRule

type EncoderRule interface {
	// StatusCode sets the HTTP response code for this error.  This will override
	// any StatusCode() method supplied on the error.
	//
	// This method returns this rule for method chaining.
	StatusCode(int) EncoderRule

	// Cause sets the cause field for this error.  This will override any Cause() method
	// supplied on the error.
	//
	// This method returns this rule for method chaining.
	Cause(string) EncoderRule

	// Headers adds header names and values according to the rules of httpaux.Header.AppendHeaders.
	// These will be added to any headers the error may define by implementing Headerer.
	//
	// This method returns this rule for method chaining.
	Headers(namesAndValues ...string) EncoderRule

	// Fields adds more JSON fields for this error.  These fields are added to the standard fields
	// and the fields an error returns through the ErrorFielder interface.  See the Fields.AddAll
	// method for how the variadic list of items is interpreted.
	//
	// This method returns this rule for method chaining.
	Fields(namesAndValues ...interface{}) EncoderRule
	// contains filtered or unexported methods
}

EncoderRule describes how to encode an error. Rules are created with either Is or As.

func As

func As(target interface{}) EncoderRule

As creates an error EncoderRule which matches using errors.As. The target must either be a pointer to an interface or a type which implements error. Any other type will cause a panic.

Because the error instance can vary, the rule created by this function dynamically determines the status code, headers, and fields using the optional interfaces defined in this package.

Any status code set explicitly on the returned rule will override whatever an error defines at runtime.

Any headers or fields set explicitly on the returned rule will be appended to whatever the error defines at runtime.

See: https://pkg.go.dev/errors#As

func Is

func Is(target error) EncoderRule

Is creates an error EncoderRule that matches a target error. errors.Is is used to determine if the returned rule matches.

The supplied target is assumed to be immutable. The status code, headers, and any extra fields are computed once and are an immutable part of the rule once it is added to an Encoder.

See: https://pkg.go.dev/errors#Is

type Error

type Error struct {
	// Err is the cause of this error.  This field is required.
	//
	// Typically, this field is set to the service-layer error or other error
	// that occurred below the presentation layer.
	Err error

	// Message is the optional message to associate with this error.
	Message string

	// Code is the response code to use for this error.  If unset, http.StatusInternalServerError
	// is used instead.
	Code int

	// Header is the optional set of HTTP headers to associate with this error.
	Header http.Header

	// Fields is the optional set of extra fields associated with this error.
	Fields Fields
}

Error is a convenient carrier of error information that exposes HTTP response information. This type implements several interfaces in popular packages like go-kit.

This type is provided for code that is HTTP-aware, e.g. the presentation tier. For more general code, prefer defining an Encoder with custom rules to define the HTTP representation of errors.

func (*Error) Cause added in v0.2.1

func (e *Error) Cause() string

Cause returns just the error's Error() result. The usage of this method is intended to be JSON or other non-plaintext representations.

func (*Error) Error

func (e *Error) Error() string

Error fulfills the error interface. Message is included in this text if it is supplied.

func (*Error) ErrorFields

func (e *Error) ErrorFields() []interface{}

ErrorFields fulfills the ErrorFielder interface and allows this error to supply additional fields that describe the error.

func (*Error) Headers

func (e *Error) Headers() http.Header

Headers returns the optional headers to associate with this error's response

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON allows this Error to be marshaled directly as JSON. The JSON representation is consistent with Encoder. However, when used with an Encoder, this method is not used.

func (*Error) StatusCode

func (e *Error) StatusCode() int

StatusCode returns the Code field, or http.StatusInternalServerError if that field is less than 100.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap produces the cause of this error

type ErrorFielder

type ErrorFielder interface {
	// ErrorFields can return any desired fields that flesh out the error.
	// The returned slice is in the same format as Fields.Add.
	ErrorFields() []interface{}
}

ErrorFielder can be implemented by errors to produce custom fields in the rendered JSON.

type Fields

type Fields map[string]interface{}

Fields holds JSON fields for an error.

func NewFields

func NewFields(code int, cause string) Fields

NewFields constructs the minimal JSON fields for an error. If code is less than 100 (the lowest value HTTP status code), then http.StatusInternalServerError is used instead.

func (Fields) Add

func (f Fields) Add(namesAndValues ...interface{})

Add adds a variadic set of names and values to this fields.

Each even-numbered item in this method's variadic arguments must be a string, or this method will panic. Each odd-numbered item is paired as the value of the preceding name. If there are an odd number of items, the last item must be a string and it is interpreted as having an nil value.

func (Fields) Append added in v0.2.1

func (f Fields) Append(nav []interface{}) []interface{}

Append does the reverse of Add. This method flattens a Fields into a sequence of {name1, value1, name2, value2, ...} values.

func (Fields) Cause added in v0.2.1

func (f Fields) Cause() string

Cause returns the cause for this set of fields. This method returns the empty string if there is no cause or if the cause is not a string.

func (Fields) Clone added in v0.2.1

func (f Fields) Clone() Fields

Clone returns a distinct, shallow copy of this Fields instance.

func (Fields) Code added in v0.2.1

func (f Fields) Code() int

Code returns the status code for this set of fields. This method returns 0 if there is no code or if the code is not an int.

func (Fields) HasCause added in v0.2.1

func (f Fields) HasCause() bool

HasCause tests if this Fields has a cause.

func (Fields) Merge

func (f Fields) Merge(more Fields)

Merge merges the fields from the given Fields into this instance.

func (Fields) SetCause

func (f Fields) SetCause(cause string)

SetCause updates the cause field.

func (Fields) SetCode

func (f Fields) SetCode(code int)

SetCode updates the code field.

type Headerer

type Headerer interface {
	Headers() http.Header
}

Headerer can be implemented by errors to produce custom headers.

type StatusCoder

type StatusCoder interface {
	// StatusCode returns the HTTP response code for an error.  Typically, this
	// will be a 4xx or 5xx code.  However, this package allows any valid HTTP
	// code to be used.
	StatusCode() int
}

StatusCoder can be implemented by errors to produce a custom status code.

Jump to

Keyboard shortcuts

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