customerror

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2022 License: MIT Imports: 5 Imported by: 3

README

customerror

customerror provides the base block to create custom errors. It also provides built-in custom errors covering some common cases. A Custom Error provides context - a Message to an optionally wrapped Err. Additionally a Code - for example "E1010", and StatusCode can be provided. Both static (pre-created), and dynamic (in-line) errors can be easily created. Code helps a company build a catalog of errors, which helps, and improves customer service.

Install

$ go get github.com/saucelabs/customerror@vX.Y.Z

Usage

See example_test.go, and customerror_test.go file.

Documentation

Run $ make doc or check out online.

Development

Check out CONTRIBUTION.

Release
  1. Update CHANGELOG accordingly.
  2. Once changes from MR are merged.
  3. Tag and release.

Roadmap

Check out CHANGELOG.

Documentation

Overview

Package customerror provides the base block to create custom errors. It also provides built-in custom errors covering some common cases. A Custom Error provides context - a `Message` to an optionally wrapped `Err`. Additionally a `Code` - for example "E1010", and `StatusCode` can be provided. Both static (pre-created), and dynamic (in-line) errors can be easily created. `Code` helps a company build a catalog of errors, which helps, and improves customer service.

Examples:

See `example_test.go` or the Example section of the GoDoc documention.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(message string, opts ...Option) error

New is the custom error factory.

Example

Demonstrates how to create static, and dynamic custom errors, also how to check, and instrospect custom errors.

// Custom static error definition.
ErrMissingID := NewMissingError("id", WithCode("E1010"))

// Some function, for demo purpose.
SomeFunc := func(id string) error {
	if id == "" {
		// Usage of the custom static error.
		return ErrMissingID
	}

	// Dynamic custom error.
	return NewFailedToError("write to disk", WithCode("E1523"))
}

// Case: Without `id`, returns `ErrMissingID`.
if err := SomeFunc(""); err != nil {
	fmt.Println(errors.Is(err, ErrMissingID)) // true

	var cE *CustomError
	if errors.As(err, &cE) {
		fmt.Println(cE.StatusCode) // 400
	}

	fmt.Println(err) // E1010: missing id (400 - Bad Request)
}

// Case: With `id`, returns dynamic error.
if err := SomeFunc("12345"); err != nil {
	var cE *CustomError
	if errors.As(err, &cE) {
		fmt.Println(cE.StatusCode) // 500
	}

	fmt.Println(err) // E1523: failed to write to disk (500 - Internal Server Error)
}
Output:

true
400
E1010: missing id
500
E1523: failed to write to disk
Example (Is)

Demonstrates error chain. `errB` will wrap `errA` and will be considered the same by propagating the chain.

errA := NewMissingError("id")
errB := NewMissingError("name", WithError(errA))

fmt.Println(errors.Is(errB, errA))
Output:

true
Example (Options)

Demonstrates how to create static, and dynamic custom errors, also how to check, and instrospect custom errors.

fmt.Println(
	NewMissingError("id", WithCode("E1010"), WithStatusCode(http.StatusNotAcceptable), WithError(errors.New("some error"))).(*CustomError).APIError(),
)
Output:

E1010: missing id (406 - Not Acceptable). Original Error: some error

func NewFailedToError

func NewFailedToError(message string, opts ...Option) error

NewFailedToError is the building block for errors usually thrown when some action failed, e.g: "Failed to create host". Default status code is `500`.

Note: Status code can be redefined, call `SetStatusCode`.

func NewInvalidError

func NewInvalidError(message string, opts ...Option) error

NewInvalidError is the building block for errors usually thrown when something fail validation, e.g: "Invalid port". Default status code is `400`.

Note: Status code can be redefined, call `SetStatusCode`.

func NewMissingError

func NewMissingError(message string, opts ...Option) error

NewMissingError is the building block for errors usually thrown when required information is missing, e.g: "Missing host". Default status code is `400`.

Note: Status code can be redefined, call `SetStatusCode`.

func NewRequiredError

func NewRequiredError(message string, opts ...Option) error

NewRequiredError is the building block for errors usually thrown when required information is missing, e.g: "Port is required". Default status code is `400`.

Note: Status code can be redefined, call `SetStatusCode`.

func Wrap

func Wrap(customError error, errors ...error) error

Wrap `customError` around `errors`.

Types

type CustomError

type CustomError struct {
	// Code can be any custom code, e.g.: E1010.
	Code string `json:"code" validate:"omitempty,startswith=E,gte=2"`

	// Err optionally wraps the original error.
	Err error `json:"-"`

	// Human readable message. Minimum length: 3.
	Message string `json:"message" validate:"required,gte=3"`

	// StatusCode is a valid HTTP status code, e.g.: 404.
	StatusCode int `json:"-" validate:"omitempty,gte=100,lte=511"`
}

CustomError is the base block to create custom errors. It provides context - a `Message` to an optional `Err`. Additionally a `Code` - for example "E1010", and `StatusCode` can be provided.

func (*CustomError) APIError added in v1.0.2

func (cE *CustomError) APIError() string

APIError is like error plus status code information.

func (*CustomError) Error

func (cE *CustomError) Error() string

Error interface implementation returns the properly formatted error message.

func (*CustomError) Is added in v1.0.0

func (cE *CustomError) Is(err error) bool

Is interface implementation ensures chain continuity. Treats `CustomError` as equivalent to `err`.

func (*CustomError) Unwrap

func (cE *CustomError) Unwrap() error

Unwrap interface implementation returns inner error.

type Option added in v1.0.0

type Option func(s *CustomError)

Option allows to define error options.

func WithCode added in v1.0.0

func WithCode(code string) Option

WithCode allows to specify an error code, such as "E1010".

func WithError added in v1.0.0

func WithError(err error) Option

WithError allows to specify an error which will be wrapped by the custom error.

func WithStatusCode added in v1.0.0

func WithStatusCode(statucCode int) Option

WithStatusCode allows to specify the status code, such as "200".

Jump to

Keyboard shortcuts

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