Categorygithub.com/micharaze/errors
modulepackage
0.4.1
Repository: https://github.com/micharaze/errors.git
Documentation: pkg.go.dev

# README

Go error handling with gRPC and HTTP error codes

This is a fork from the error handling example https://github.com/henrmota/errors-handling-example.

Additional to the fork I implemented gRPC and HTTP error codes for simplify error handling in gRPC or HTTP communications. The descriptions of the error codes can be found here: https://cloud.google.com/apis/design/errors#error_model.

This library is wrapped from https://github.com/pkg/errors.

Creating a typed errors is as easy:

errors.InvalidArgument.New("error parsing the input information")

You can create an untyped error as easy as:

errors.New("an untyped error")

Adding a new context to an existing error:

errors.AddContext(err, "field", "message")

In the top layer when you decide to log or return a web response:

errors.GetType(err) == errors.InvalidArgument // true
errors.GetContext(err) // map[string]string{"field": "field", "message": "message"}

Converting error type in gRPC error code:

errors.OutOfRange.New("an untyped error").Code()

or in HTTP code:

errors.OutOfRange.New("an untyped error").HTTP()

To add new error type is just adding a new constant to errors

const (
  // InvalidArgument error
  InvalidArgument ErrorType = ErrorType(codes.InvalidArgument)
  // FailedPrecondition error
  FailedPrecondition ErrorType = ErrorType(codes.FailedPrecondition)
  // OutOfRange error
  OutOfRange ErrorType = ErrorType(codes.OutOfRange)
  ...
  //ADD here
)

and to httpMap for converting to http code

var httpMap = map[ErrorType]uint32{
  InvalidArgument:    400,
  FailedPrecondition: 400,
  OutOfRange:         400,
  ...
  //ADD here
}

# Functions

AddErrorContext adds a context to an error.
Cause gives the original error.
GetErrorContext returns the error context.
GetType returns the error type.
New creates a no type error.
NewCode creates an error by given gRPC Code and message.
NewCodef creates an error by given gRPC Code and formatted message.
Newf creates a no type error with formatted message.
Wrap an error with a string.
Wrapf an error with format string.

# Constants

Aborted error.
AlreadyExists error.
Canceled error.
DataLoss error.
DeadlineExceeded error.
FailedPrecondition error.
Internal error.
InvalidArgument error.
NotFound error.
OutOfRange error.
PermissionDenied error.
ResourceExhausted error.
Unauthenticated error.
Unavailable error.
Unimplemented error.
Unknown error.

# Type aliases

ErrorType is the type of an error.