errors

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2023 License: MIT Imports: 8 Imported by: 2

Documentation

Overview

Package errors provides a generic error carrying useful information:

  • 2 different messages: one for the end user and one for the developer
  • a Kind: a string that can act as an ID for errors
  • a httpStatus
  • a timestamp of when the error was created

This error implement the json.Marshaler and xml.Marshaler interface, so you can return this error in your http handlers.

It also implements the errors.Unwrap interface, allowing you to get the previous error.

It depends on the gapi/log package, as the error will implement several of its interfaces to log the errors correctly.

## Create a new error

To create a new error, simply call the Err() function and use the setter to set any data you want.

The setter functions will modify the data and won't create a new error, you don't need to reassign the error.

import (
	"net/http"
	"github.com/mwm-io/gapi/errors"
)

err := errors.Err("my error).
	WithKind("not_found").
	WithStatusCode(http.StatusNotFound).
	WithMessage("not found")

## Wrap an existing error

To wrap an existing error, simply call the Wrap() function. You can then modify the new error as you want.

Wrapping a nil error will return a nil value.

import (
	"fmt"
	"github.com/mwm-io/gapi/errors"
)

err := fmt.Errorf("source error")
newErr := errors.Wrap(err, "error").WithKind("new_kind")

### Populate data from the source error

You might want to carry more than just the message type from the source error.

In order to do that you need to implement the ErrorBuilder interface and register your builder with an init function.

Your builder should concern a single type of error.

You can read an example with the errors/google package.

import (
	"github.com/mwm-io/gapi/errors"
)

func init() {
	errors.AddBuilder()
}

var GrpcCodeErrorBuilder = errors.ErrorBuilderFunc(func(err errors.Error, sourceError error) errors.Error {
	sourceErrI, ok := sourceErr.(interface{ WithKind() string })
	if !ok {
		return err
	}

	return err.WithKind(sourceErrI.WithKind())
})

## Why is it an interface ?

You may wonder why we use an Error interface and why don't we use the FullError struct directly.

This is because `(*FullError)(nil) != nil`: a nil value with a concrete type won't match nil.

In order to keep the idiomatic `if Err("my err") != nil`, we always return the Error interface.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddErrorBuilders added in v0.2.2

func AddErrorBuilders(builders ...ErrorBuilder)

AddErrorBuilders appends custom errors.ErrorBuilder. These callbacks are executed when wrapping an error with errors.Wrap().

func GetCallers added in v0.2.4

func GetCallers() (callerName, caller string, callStack []string)

GetCallers return the caller of the function and the call stack

Types

type Error

type Error interface {
	error
	Unwrap() error
	json.Marshaler
	xml.Marshaler
	Message() string
	Kind() string
	StatusCode() int
	Timestamp() time.Time
	CallerName() string
	Caller() string
	Callstack() []string

	WithMessage(format string, args ...interface{}) Error
	WithKind(string) Error
	WithStatus(int) Error
	WithError(error) Error
}

Error represents the interface for the FullError struct. It is necessary so we can compare nil errors. (nil.(*FullError) != nil)

func BadGateway added in v0.0.8

func BadGateway(kind, msgFormat string, args ...interface{}) Error

BadGateway return an error with status code http.StatusBadGateway

func BadRequest added in v0.0.8

func BadRequest(kind, msgFormat string, args ...interface{}) Error

BadRequest return an error with status code http.StatusBadRequest

func Conflict added in v0.0.8

func Conflict(kind, msgFormat string, args ...interface{}) Error

Conflict return an error with status code http.StatusConflict

func Err

func Err(kind, format string, args ...interface{}) Error

Err creates a new Error.

func ExpectationFailed added in v0.0.8

func ExpectationFailed(kind, msgFormat string, args ...interface{}) Error

ExpectationFailed return an error with status code http.StatusExpectationFailed

func FailedDependency added in v0.0.8

func FailedDependency(kind, msgFormat string, args ...interface{}) Error

FailedDependency return an error with status code http.StatusFailedDependency

func Forbidden added in v0.0.8

func Forbidden(kind, msgFormat string, args ...interface{}) Error

Forbidden return an error with status code http.StatusForbidden

func GatewayTimeout added in v0.0.8

func GatewayTimeout(kind, msgFormat string, args ...interface{}) Error

GatewayTimeout return an error with status code http.StatusGatewayTimeout

func Gone added in v0.0.8

func Gone(kind, msgFormat string, args ...interface{}) Error

Gone return an error with status code http.StatusGone

func HTTPVersionNotSupported added in v0.0.8

func HTTPVersionNotSupported(kind, msgFormat string, args ...interface{}) Error

HTTPVersionNotSupported return an error with status code http.StatusHTTPVersionNotSupported

func InsufficientStorage added in v0.0.8

func InsufficientStorage(kind, msgFormat string, args ...interface{}) Error

InsufficientStorage return an error with status code http.StatusInsufficientStorage

func InternalServerError added in v0.0.8

func InternalServerError(kind, msgFormat string, args ...interface{}) Error

InternalServerError return an error with status code http.StatusInternalServerError

func LengthRequired added in v0.0.8

func LengthRequired(kind, msgFormat string, args ...interface{}) Error

LengthRequired return an error with status code http.StatusLengthRequired

func Locked added in v0.0.8

func Locked(kind, msgFormat string, args ...interface{}) Error

Locked return an error with status code http.StatusLocked

func LoopDetected added in v0.0.8

func LoopDetected(kind, msgFormat string, args ...interface{}) Error

LoopDetected return an error with status code http.StatusLoopDetected

func MethodNotAllowed added in v0.0.8

func MethodNotAllowed(kind, msgFormat string, args ...interface{}) Error

MethodNotAllowed return an error with status code http.StatusMethodNotAllowed

func MisdirectedRequest added in v0.0.8

func MisdirectedRequest(kind, msgFormat string, args ...interface{}) Error

MisdirectedRequest return an error with status code http.StatusMisdirectedRequest

func NetworkAuthenticationRequired added in v0.0.8

func NetworkAuthenticationRequired(kind, msgFormat string, args ...interface{}) Error

NetworkAuthenticationRequired return an error with status code http.StatusNetworkAuthenticationRequired

func NotAcceptable added in v0.0.8

func NotAcceptable(kind, msgFormat string, args ...interface{}) Error

NotAcceptable return an error with status code http.StatusNotAcceptable

func NotExtended added in v0.0.8

func NotExtended(kind, msgFormat string, args ...interface{}) Error

NotExtended return an error with status code http.StatusNotExtended

func NotFound added in v0.0.8

func NotFound(kind, msgFormat string, args ...interface{}) Error

NotFound return an error with status code http.StatusNotFound

func NotImplemented added in v0.0.8

func NotImplemented(kind, msgFormat string, args ...interface{}) Error

NotImplemented return an error with status code http.StatusNotImplemented

func PaymentRequired added in v0.0.8

func PaymentRequired(kind, msgFormat string, args ...interface{}) Error

PaymentRequired return an error with status code http.StatusPaymentRequired

func PreconditionFailed added in v0.0.8

func PreconditionFailed(kind, msgFormat string, args ...interface{}) Error

PreconditionFailed return an error with status code http.StatusPreconditionFailed

func PreconditionRequired added in v0.0.8

func PreconditionRequired(kind, msgFormat string, args ...interface{}) Error

PreconditionRequired return an error with status code http.StatusPreconditionRequired

func ProxyAuthRequired added in v0.0.8

func ProxyAuthRequired(kind, msgFormat string, args ...interface{}) Error

ProxyAuthRequired return an error with status code http.StatusProxyAuthRequired

func RequestEntityTooLarge added in v0.0.8

func RequestEntityTooLarge(kind, msgFormat string, args ...interface{}) Error

RequestEntityTooLarge return an error with status code http.StatusRequestEntityTooLarge

func RequestHeaderFieldsTooLarge added in v0.0.8

func RequestHeaderFieldsTooLarge(kind, msgFormat string, args ...interface{}) Error

RequestHeaderFieldsTooLarge return an error with status code http.StatusRequestHeaderFieldsTooLarge

func RequestTimeout added in v0.0.8

func RequestTimeout(kind, msgFormat string, args ...interface{}) Error

RequestTimeout return an error with status code http.StatusRequestTimeout

func RequestURITooLong added in v0.0.8

func RequestURITooLong(kind, msgFormat string, args ...interface{}) Error

RequestURITooLong return an error with status code http.StatusRequestURITooLong

func RequestedRangeNotSatisfiable added in v0.0.8

func RequestedRangeNotSatisfiable(kind, msgFormat string, args ...interface{}) Error

RequestedRangeNotSatisfiable return an error with status code http.StatusRequestedRangeNotSatisfiable

func ServiceUnavailable added in v0.0.8

func ServiceUnavailable(kind, msgFormat string, args ...interface{}) Error

ServiceUnavailable return an error with status code http.StatusServiceUnavailable

func Teapot added in v0.0.8

func Teapot(kind, msgFormat string, args ...interface{}) Error

Teapot return an error with status code http.StatusTeapot

func TooEarly added in v0.0.8

func TooEarly(kind, msgFormat string, args ...interface{}) Error

TooEarly return an error with status code http.StatusTooEarly

func TooManyRequests added in v0.0.8

func TooManyRequests(kind, msgFormat string, args ...interface{}) Error

TooManyRequests return an error with status code http.StatusTooManyRequests

func Unauthorized added in v0.0.8

func Unauthorized(kind, msgFormat string, args ...interface{}) Error

Unauthorized return an error with status code http.StatusUnauthorized

func UnavailableForLegalReasons added in v0.0.8

func UnavailableForLegalReasons(kind, msgFormat string, args ...interface{}) Error

UnavailableForLegalReasons return an error with status code http.StatusUnavailableForLegalReasons

func UnprocessableEntity added in v0.0.8

func UnprocessableEntity(kind, msgFormat string, args ...interface{}) Error

UnprocessableEntity return an error with status code http.StatusUnprocessableEntity

func UnsupportedMediaType added in v0.0.8

func UnsupportedMediaType(kind, msgFormat string, args ...interface{}) Error

UnsupportedMediaType return an error with status code http.StatusUnsupportedMediaType

func UpgradeRequired added in v0.0.8

func UpgradeRequired(kind, msgFormat string, args ...interface{}) Error

UpgradeRequired return an error with status code http.StatusUpgradeRequired

func VariantAlsoNegotiates added in v0.0.8

func VariantAlsoNegotiates(kind, msgFormat string, args ...interface{}) Error

VariantAlsoNegotiates return an error with status code http.StatusVariantAlsoNegotiates

func Wrap

func Wrap(err error) Error

Wrap will wrap the given error and return a new Error.

type ErrorBuilder

type ErrorBuilder func(err error) Error

ErrorBuilder is a callback that transform the given error to a gapi Error.

type FullError

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

FullError is a concrete error that implements the Error interface

func (*FullError) Caller added in v0.2.4

func (e *FullError) Caller() string

Caller implements the error interface. It will return the name of the function that created the error

func (*FullError) CallerName added in v0.2.4

func (e *FullError) CallerName() string

CallerName implements the error interface. It will return the name of the function that created the error

func (*FullError) Callstack added in v0.2.4

func (e *FullError) Callstack() []string

Callstack implements the error interface. It will return the complete callstack of the error creation

func (*FullError) Error

func (e *FullError) Error() string

FullError implements the error interface. It will return the "developer" message in opposition to the user message, which is returned by FullError.Message

func (*FullError) Kind

func (e *FullError) Kind() string

Kind returns the error kind.

func (*FullError) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface.

func (*FullError) MarshalXML

func (e *FullError) MarshalXML(encoder *xml.Encoder, start xml.StartElement) error

MarshalXML implements the xml.Marshaler interface.

func (*FullError) Message

func (e *FullError) Message() string

Message returns the user message.

func (*FullError) StatusCode

func (e *FullError) StatusCode() int

StatusCode implements server.WithStatusCode

func (*FullError) Timestamp

func (e *FullError) Timestamp() time.Time

Timestamp returns the error timestamp.

func (*FullError) Unwrap

func (e *FullError) Unwrap() error

Unwrap implements the errors.Unwrap interface

func (*FullError) WithError added in v0.2.3

func (e *FullError) WithError(err error) Error

WithError wrap source error.

func (*FullError) WithKind

func (e *FullError) WithKind(kind string) Error

WithKind sets the error kind.

func (*FullError) WithMessage

func (e *FullError) WithMessage(format string, args ...interface{}) Error

WithMessage sets the user message.

func (*FullError) WithStatus

func (e *FullError) WithStatus(status int) Error

WithStatus sets the error status. It will also modify the severity for status >= 400

type HttpError

type HttpError struct {
	Message string `json:"message" xml:"message"`
	Kind    string `json:"kind" xml:"kind"`
}

HttpError is used to json.Marshal or xml.Marshal FullError. You can use it to decode an incoming error.

Jump to

Keyboard shortcuts

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