globalerrors

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

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

Go to latest
Published: Aug 28, 2023 License: MIT Imports: 3 Imported by: 0

README

Global errors golang package

Table of Contents

  1. Overview
  2. Installation
  3. Usage
  4. API
  5. Custom Errors
  6. Contributing
  7. License

Overview

The globalerrors package provides a convenient way to map custom errors to both HTTP and gRPC status codes. This helps in ensuring consistency in error handling across different service architectures.

Installation

To install this package, you can run:

go get -u github.com/thefabric-io/globalerrors

Usage

HTTP Status Codes

The package offers an HTTPStatus function which accepts a custom error as an argument and returns the corresponding HTTP status code.

import (
  "github.com/thefabric-io/globalerrors"
)

func main() {
  err := globalerrors.BadRequest
  statusCode := globalerrors.HTTPStatus(err)
  // statusCode will be http.StatusBadRequest (400)
}
gRPC Status Codes

Similarly, the GRPCStatus function accepts a custom error and returns the gRPC status code.

import (
  "github.com/thefabric-io/globalerrors"
)

func main() {
  err := globalerrors.BadRequest
  statusCode := globalerrors.GRPCStatus(err)
  // statusCode will be codes.InvalidArgument
}

API

HTTPStatus

Syntax:

func HTTPStatus(customError error) int
  • customError: The custom error for which you want to find the HTTP status code.

Returns: Corresponding HTTP status code as an integer.

GRPCStatus

Syntax:

func GRPCStatus(customError error) codes.Code
  • customError: The custom error for which you want to find the gRPC status code.

Returns: Corresponding gRPC status code.

Custom Error Example

You can define custom errors that implement the error interface and use them with the globalerrors package. Here's an example:

import (
	"errors"
	
	"github.com/thefabric-io/globalerrors"
)

func ErrIDIsRequired() error {
	return errIDIsRequired{}
}

type errIDIsRequired struct{}

func (e errIDIsRequired) Error() string {
	return "id is required"
}

func (e errIDIsRequired) Is(target error) bool {
	return errors.Is(target, globalerrors.InternalServerError) || e == target
}

// Usage
func main() {
	err := ErrIDIsRequired()
	httpStatusCode := globalerrors.HTTPStatus(err)
	grpcStatusCode := globalerrors.GRPCStatus(err)

	// Since `ErrIDIsRequired` is defined to be equivalent to `globalerrors.InternalServerError`,
	// httpStatusCode will be http.StatusInternalServerError (500)
	// grpcStatusCode will be codes.Internal
}

In this example, we have defined a custom error ErrIDIsRequired that implements the error interface. We have also defined an Is method to make it compatible with errors.Is, enabling it to be used with the globalerrors package.


Custom Errors Extensions

You can also extend the package to include your custom errors and their corresponding status codes.

  1. Add your custom error in the globalErrors slice.
var globalErrors = []error{
  ...
  YourCustomError,
  ...
}
  1. Update httpStatusCodesMap and/or grpcStatusCodesMap to include the status code mapping for your custom error.
var httpStatusCodesMap = map[error]int{
  ...
  YourCustomError: http.YourStatusCode,
  ...
}

var grpcStatusCodesMap = map[error]codes.Code{
  ...
  YourCustomError: codes.YourStatusCode,
  ...
}

Contributing

We welcome contributions to this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details.


For further details and queries, please feel free to reach out.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	BadRequest                    = errors.New("bad request")
	Unauthorized                  = errors.New("unauthorized")
	PaymentRequired               = errors.New("payment required")
	Forbidden                     = errors.New("forbidden")
	NotFound                      = errors.New("not found")
	MethodNotAllowed              = errors.New("method not allowed")
	NotAcceptable                 = errors.New("not acceptable")
	ProxyAuthRequired             = errors.New("proxy authentication required")
	RequestTimeout                = errors.New("request timeout")
	Conflict                      = errors.New("conflict")
	Gone                          = errors.New("gone")
	LengthRequired                = errors.New("length required")
	PreconditionFailed            = errors.New("precondition failed")
	RequestEntityTooLarge         = errors.New("request entity too large")
	RequestURITooLong             = errors.New("request URI too long")
	UnsupportedMediaType          = errors.New("unsupported media type")
	RequestedRangeNotSatisfiable  = errors.New("requested range not satisfiable")
	ExpectationFailed             = errors.New("expectation failed")
	Teapot                        = errors.New("I'm a teapot")
	MisdirectedRequest            = errors.New("misdirected request")
	UnprocessableEntity           = errors.New("unprocessable entity")
	Locked                        = errors.New("locked")
	FailedDependency              = errors.New("failed dependency")
	TooEarly                      = errors.New("too early")
	UpgradeRequired               = errors.New("upgrade required")
	PreconditionRequired          = errors.New("precondition required")
	TooManyRequests               = errors.New("too many requests")
	RequestHeaderFieldsTooLarge   = errors.New("request header fields too large")
	UnavailableForLegalReasons    = errors.New("unavailable for legal reasons")
	InternalServerError           = errors.New("internal server error")
	NotImplemented                = errors.New("not implemented")
	BadGateway                    = errors.New("bad gateway")
	ServiceUnavailable            = errors.New("service unavailable")
	GatewayTimeout                = errors.New("gateway timeout")
	HTTPVersionNotSupported       = errors.New("HTTP version not supported")
	VariantAlsoNegotiates         = errors.New("variant also negotiates")
	InsufficientStorage           = errors.New("insufficient storage")
	LoopDetected                  = errors.New("loop detected")
	NotExtended                   = errors.New("not extended")
	NetworkAuthenticationRequired = errors.New("network authentication required")
)

Functions

func GRPCStatus

func GRPCStatus(customError error) codes.Code

func HTTPStatus

func HTTPStatus(customError error) int

Types

This section is empty.

Jump to

Keyboard shortcuts

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