errs

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2024 License: MIT Imports: 6 Imported by: 10

README

errs CI Test codecov

This package provides a simple error type that can be used to map errors to HTTP and GRPC status codes.

It is heavily inspired by encore.dev/beta/errs but adds support for GRPC codes.

Usage

package main

import (
	"fmt"
	"github.com/lordvidex/errs"
	"encoding/json"
)

func main() {
	err := errs.B().Code(errs.NotFound).Msg("user not found").Err()
	// err.Error() == "user not found"
	// err.HTTPCode() == 404
	// err.GRPCCode() == 5
	b, _ := json.Marshal(err)
	fmt.Println(string(b)) 
	// Outputs: {"code":"not_found", "message":"user not found"}
}
  • check the tests for more usage and examples

Codes

Code HTTP Status GRPC Code Name
0 http.StatusInternalServerError codes.Unknown Unknown Code
1 499 codes.Canceled Canceled
2 http.StatusBadRequest codes.InvalidArgument InvalidArgument
3 http.StatusGatewayTimeout codes.DeadlineExceeded DeadlineExceeded
4 http.StatusUnauthorized codes.Unauthenticated Unauthenticated
5 http.StatusNotFound codes.NotFound NotFound
6 http.StatusConflict codes.AlreadyExists AlreadyExists
7 http.StatusForbidden codes.PermissionDenied Forbidden
8 http.StatusTooManyRequests codes.ResourceExhausted ResourceExhausted
9 http.StatusPreconditionFailed codes.FailedPrecondition FailedPrecondition
10 http.StatusConflict codes.Aborted Aborted
11 httpStatusRequestedRangeNotSatisfiable codes.OutOfRange OutOfRange
12 http.StatusInternalServerError codes.Internal Internal
13 http.StatusServiceUnavailable codes.Unavailable Unavailable
14 http.StatusInternalServerError codes.DataLoss DataLoss

References

  • google.golang.org/grpc/codes for grpc codes

Documentation

Index

Examples

Constants

View Source
const CodeSize = 15

CodeSize is the number of codes defined in the STL library. All codes defined by default are mapped from 0 to CodeSize - 1. CodeSize can be useful when creating additional codes for example:

const (
	// MyCode is a custom code.
	MyCode Code = errs.CodeSize + iota // = 15
 	ExtraCode // = 16
)

Variables

View Source
var Separator = ": "

Separator is the default separator between elements of a single error

Functions

func ClearCodeRegister added in v0.2.0

func ClearCodeRegister()

ClearCodeRegister removes all registration made with the function RegisterCode

func Convert added in v1.0.0

func Convert(err error) error

Convert converts any error to an *Error type. If the error is already an *Error, it is returned as is. nil errors are returned as nil.

func IsRegistered added in v0.2.0

func IsRegistered(c Code) bool

IsRegistered returns true if a custom implementation or override is being used for the code.

func RegisterCode added in v0.2.0

func RegisterCode(c Code, HTTP int, GRPC codes.Code, desc string)

RegisterCode registers a new code OR overrides an existing one.

func UnregisterCode added in v0.2.0

func UnregisterCode(c Code)

UnregisterCode unregisters the custom implementation or override of a code provided from the RegisterCode function. When a code is unregistered, UnregisterCode is a no-op.

func Wrap

func Wrap(child, parent error) error

Wrap wraps an underlying error `child` with a new error `parent`.

- when the child error is nil, the parent error is returned as is.

- when the parent error is nil, the child error is returned as is.

- when both errors are nil, nil is returned.

func WrapCode

func WrapCode(err error, code Code, messages ...string) error

WrapCode wraps an underlying error with a new error, adding message to the error's previously existing message and setting the error code to code.

func WrapMsg added in v1.0.0

func WrapMsg(err error, message ...string) error

WrapMsg wraps an underlying error with a new error, adding message to the error's previously existing message

Types

type Builder

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

Builder is used to build an instance of `Error` object.

Example
b := B().Code(Unknown).Msg("unknown error").Details("details")
fmt.Println(b.Err())
Output:

unknown: unknown error

func B

func B(initial ...error) *Builder

B returns a new error builder. Optionally, you can pass an error instance to the builder, ONLY the first error will be used.

Possible cases:

1. B() -> new error

2. B(err) -> update existing error (because of pointers) and returns it after calling Err()

3. B(err1, err2, err3) -> updates only err1 and returns it after calling Err()

func WrapB added in v1.2.0

func WrapB(err error) *Builder

WrapB wraps an underlying error and returns a builder for the new error.

func (*Builder) Code

func (b *Builder) Code(code Code) *Builder

Code sets the code of the error.

func (*Builder) Details

func (b *Builder) Details(details ...any) *Builder

Details adds details to the error.

func (*Builder) Err

func (b *Builder) Err() error

Err returns new instance of `Error`.

func (*Builder) Msg

func (b *Builder) Msg(msg ...string) *Builder

Msg sets the message of the error.

func (*Builder) Msgf

func (b *Builder) Msgf(format string, parameters ...any) *Builder

Msgf formats the message using the given format and parameters, similar to fmt.Sprintf.

Example
b := B().Code(NotFound).Msgf("file not found: %s, %d", "details", 123).Op("File.Open")
err := b.Err()
str, _ := json.Marshal(err)
fmt.Println(string(str))
Output:

{"op":"File.Open","message":["file not found: details, 123"],"code":"not_found"}

func (*Builder) Op added in v1.2.0

func (b *Builder) Op(op string) *Builder

Op sets the operation where the error occured

func (*Builder) Show added in v1.2.0

func (b *Builder) Show() *Builder

Show sets the show flag of the error. If this error is wrapped by another error, it's shown to users.

type Code

type Code int

Code is the type that represents an error code. It can map to HTTP and gRPC codes. In order to properly work with custom codes or code overrides: use the RegisterCode function after creating your new Code instance.

const (
	// Unknown is the default error code.
	Unknown Code = iota

	// Canceled indicates the operation was canceled or unavailable because it was cancelled.
	Canceled

	// InvalidArgument is used when the client sends invalid arguments.
	InvalidArgument

	// DeadlineExceeded means operation expired before completion. This doesn't necessarily mean that the operation failed.
	// It is possible that the operation succeeded but the deadline was exceeded.
	DeadlineExceeded

	// Unauthenticated is used when the client is not authenticated.
	Unauthenticated

	// NotFound is used when the requested resource is not found.
	NotFound

	// AlreadyExists is used when the resource already exists.
	AlreadyExists

	// Forbidden is used when the client is not authorized to perform the requested operation.
	Forbidden

	// ResourceExhausted is used when the client has exhausted some resource.
	ResourceExhausted

	// FailedPrecondition is used when the client sends a request that is not allowed in the current state.
	FailedPrecondition

	// Aborted is used when the client sends a request that cannot be completed due to a conflict e.g. a concurrency issue.
	Aborted

	// OutOfRange means that the operation was attempted past the valid range.
	OutOfRange

	// Internal is used when an internal error occurs.
	Internal

	// Unavailable is used when the service cannot be reached due to some network issues.
	Unavailable

	// DataLoss is used when the service has lost some data.
	DataLoss
)

func (Code) GRPC

func (c Code) GRPC() codes.Code

GRPC returns the gPRC code that is mapped to the code.

func (Code) HTTP

func (c Code) HTTP() int

HTTP returns the HTTP code that is mapped to the code.

func (Code) MarshalJSON

func (c Code) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface and defines how a Code should be marshaled to JSON. By default, it marshals to a string representation defined by String function.

func (Code) String

func (c Code) String() string

String returns the string representation of the code.

type Error

type Error struct {

	// Op operation where error occured
	Op string `json:"op"`

	// Msg is the user-friendly message returned to the client.
	Msg []string `json:"message"`

	// Details is the internal error message returned to the developer.
	Details []any `json:"-"`

	// Code is the error code of the error. When marshaled to JSON, it will be a string.
	Code Code `json:"code"`
	// contains filtered or unexported fields
}

func (*Error) Error

func (e *Error) Error() string

Error returns the error in the format "code: message\ninner_code: inner_message" for this error and SHOWN underlying errors.

Example
err := B().Code(NotFound).Msg("item not found").Op("FetchItem").Err()
fmt.Println(err.Error())
Output:

not_found: FetchItem: item not found

func (*Error) Is added in v1.1.0

func (e *Error) Is(target error) bool

func (*Error) Stack added in v1.0.0

func (e *Error) Stack() []string

Stack returns a description of the error and all it's underlying errors.

Example
err1 := B().Code(NotFound).Msg("item not found").Err()
err2 := B().Code(Internal).Msg("internal error").Err()
err, _ := Wrap(err2, err1).(*Error)
fmt.Print(err.Stack())
Output:

func (*Error) String added in v1.2.0

func (e *Error) String() string

String returns the error in the format "code: message".

func (*Error) Unwrap added in v1.0.0

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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