grpcerr

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

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

Go to latest
Published: Jul 21, 2021 License: MIT Imports: 7 Imported by: 0

README

TL;DR

This library enables API developers to use the gRPC error model for both gRPC and HTTP. It provides an easy to use API for instantiating gRPC errors such as Unavailable, Resource Exhausted, Invalid argument etc, in addition to easily adding metadata such as a request ID, stack traces and more. It also facilitates encoding and writing of gRPC errors to an http.ResponseWriter. As of now, it only supports JSON-encoding.

Getting Started

So you want to get started using this library? Follow the instructions in this section.

Installation

Given the project that wants to use this library is using Go Modules, installing it is as easy as entering the following command:

go get github.com/tobbstr/grpcerr

This'll add it to the list of dependencies in the go.mod file.

Usage

Instantiation of a gRPC error

import (
    "github.com/tobbstr/grpcerr"
	"google.golang.org/genproto/googleapis/rpc/errdetails"
)

func main() {
    // Error details
    errInfo := &grpcerr.ErrorInfo{
        Reason: "Token expired",
        Domain: "Authorization",
        Metadata: map[string]string{
            "TokenExpired": "2006-01-02 15:04:05",
        },
    }

    // Instantiation of the gRPC error
    permissionDenied, err := grpcerr.NewPermissionDenied("", errInfo)
    if err != nil {
        // handle error
    }
}

Returning gRPC error from an HTTP API

import (
    "net/http"
    "github.com/tobbstr/grpcerr"
	"google.golang.org/genproto/googleapis/rpc/errdetails"
)

// controller definition omitted

func (c *controller) awesomeEndpoint(w http.ResponseWriter, r *http.Request) {
    // ... Do bunch of stuff ...

    err = vitalFunc(...)
    // Handles errors returned from an invocation.
    // Note! err must be a gRPC error instantiated using this library
    if err != nil {
        encodeAndWrite := grpcerr.NewHttpResponseEncodeWriter(w)
        if err = encodeAndWrite(err).AsJSON(); err != nil {
            // Log and handle error. The error should normally be nil.
        }
        return
    }

    // Continue normal processing...
}

This is an example of a HTTP Response Body for an InvalidArgument gRPC error:

{
    "code":3,
    "message":"dummy-msg",
    "details":[
        {
            "@type":"type.googleapis.com/google.rpc.BadRequest",
            "fieldViolations":[
                {
                    "field":"dummy-field-violation-field",
                    "description":"dummy-field-violation-desc"
                }
            ]
        }
    ]
}

In terms of HTTP headers the HTTP status code is translated from the gRPC error code, but is overridable using options when calling grpcerr.NewHttpRresponseEncodeWriter(w, opts...). The below is an example of this:

// defining the override
withStatusOK := func(w http.ResponseWriter) {
    w.WriteHeader(http.StatusOK)
}

// use the option like this
encodeAndWrite := NewHttpResponseEncodeWriter(w, withStatusOK)

Wrapping of errors are supported

// Somewhere in a service far, far away...
func (svc *service) OrchestrateImportantAction() error {
    // Something goes awry
    if err != nil {
        violations := []grpcerr.PreconditionFailure{
            {
                Type: "Account missing",
                Subject: "john.doe@example.com",
                Description: "Callers must supply account information in request",
            },
        }

        failedPrecondition, err := grpcerr.NewFailedPrecondition("", violations)
        if err != nil {
            // handle error
        }

        // Note! The returned error is a wrapped one, having the gRPC error as its root error. It does not matter how many times the gRPC error gets wrapped, as long as it's the root error.
        return fmt.Errorf("could not perform something cool: %w", failedPrecondition)
    }
}

// Meanwhile in an HTTP controller not that far away
func (c *controller) performImportantAction(w http.ResponseWriter, r *http.Request) {
    // invoke svc, which returns a wrapped gRPC error instantiated using this library
    err := c.svc.OrchestrateImportantAction()
    if err != nil {
        // ... Log the error ...

        // write an HTTP response from the root error which is the gRPC error
        encodeAndWrite := grpcerr.NewHttpResponseEncodeWriter(w)
        if err = encodeAndWrite(err).AsJSON(); err != nil {
            // handle error
        }
        return
    }
}

Using gRPC errors in gRPC APIs

func (c *gRPCController) AwesomeEndpoint(ctx context.Context, req *AwesomeRequest) (*AwesomeResponse, error) {
    err := c.svc.OrchestrateImportantAction()
    if err != nil {
        // ... Log the error ...

        // no additional processing required, return the error as is
        return nil, err
    }
}

Using gRPC errors in gRPC clients

response, err := client.AwesomeEndpoint(...)
if err != nil {
    // gets the gRPC code
    code := grpcerr.Code(err)

    // gets the gRPC message
    message := grpcerr.Message(err)

    // gets the RequestInfo from the gRPC error
    requestInfo := grpcerr.RequestInfoFrom(err)

    // gets the DebugInfo from the gRPC error
    debugInfo := grpcerr.DebugInfoFrom(err)

    // gets the HelpLinks from the gRPC error
    helpLinks := grpcerr.HelpLinksFrom(err)

    // gets the LocalizedMessage from the gRPC error
    localizedMessage := grpcerr.LocalizedMessageFrom(err)

    // gets the QuotaViolations from the gRPC error
    quotaViolations := grpcerr.QuotaViolationsFrom(err)

    // gets the FieldViolations from the gRPC error
    fieldViolations := grpcerr.FieldViolationsFrom(err)

    // etc ...
}

Roadmap

See the open issues for a list of proposed features (and known issues).

Contributing

Contributing can be done in more than one way. One way is to hit the star button. Another is to add to or improve the existing repo content. The following steps guide you how to do that. In any case, contributions are greatly appreciated.

  1. Clone this repo by entering this command in a terminal
    git clone https://github.com/tobbstr/grpcerr.git
    
  2. Navigate to the repo folder
  3. Create a feature branch
    git checkout -b feature-name
    
  4. Make the changes you want and commit them
  5. Push the branch to GitHub
    git push origin feature-name
    
  6. Open a pull request

License

Distributed under the MIT license.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddDebugInfo

func AddDebugInfo(gRPCErr error, debugInfo *DebugInfo) (error, error)

AddDebugInfo adds additional debug info to a gRPC error. For example useful when the server wants to include a stack trace.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func AddHelp

func AddHelp(gRPCErr error, links []HelpLink) (error, error)

AddHelp adds links to a gRPC error to documentation or for performing an out of band action.

For example, if a quota check failed with an error indicating the calling project hasn't enabled the accessed service, this can contain a URL pointing directly to the right place in the developer console to flip the bit.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func AddLocalizedMessage

func AddLocalizedMessage(gRPCErr error, localizedMsg *LocalizedMessage) (error, error)

AddLocalizedMessage adds a localized error message to a gRPC error

func AddRequestInfo

func AddRequestInfo(gRPCErr error, requestInfo *RequestInfo) (error, error)

AddRequestInfo adds metadata to a gRPC error about the request that clients can attach when filing a bug or providing other forms of feedback.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func Code

func Code(gRPCErr error) codes.Code

func Message

func Message(gRPCErr error) string

func NewAborted

func NewAborted(errMsg string, errorInfo *ErrorInfo) (error, error)

NewAborted constructs a gRPC error that indicates the operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc.

See litmus test above for deciding between FailedPrecondition, Aborted, and Unavailable.

This error code will not be generated by the gRPC framework.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewAlreadyExists

func NewAlreadyExists(errMsg string, resourceInfo *ResourceInfo) (error, error)

NewAlreadyExists constructs a gRPC error that means an attempt to create an entity failed because one already exists.

This error code will not be generated by the gRPC framework.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewCancelled

func NewCancelled(errMsg string) error

NewCancelled constructs a gRPC error that indicates the operation was canceled (typically by the caller).

The gRPC framework will generate this error code when cancellation is requested.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewDataLoss

func NewDataLoss(errMsg string, debugInfo *DebugInfo) (error, error)

NewDataLoss constructs a gRPC error that indicates unrecoverable data loss or corruption.

This error code will not be generated by the gRPC framework.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewDeadlineExceeded

func NewDeadlineExceeded(errMsg string, debugInfo *DebugInfo) (error, error)

NewDeadlineExceeded constructs a gRPC error that means operation expired before completion. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire.

The gRPC framework will generate this error code when the deadline is exceeded.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewFailedPrecondition

func NewFailedPrecondition(errMsg string, failures []PreconditionFailure) (error, error)

NewFailedPrecondition constructs a gRPC error that indicates operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to a non-directory, etc.

A litmus test that may help a service implementor in deciding between FailedPrecondition, Aborted, and Unavailable:

(a) Use Unavailable if the client can retry just the failing call.
(b) Use Aborted if the client should retry at a higher-level
    (e.g., restarting a read-modify-write sequence).
(c) Use FailedPrecondition if the client should not retry until
    the system state has been explicitly fixed. E.g., if an "rmdir"
    fails because the directory is non-empty, FailedPrecondition
    should be returned since the client should not retry unless
    they have first fixed up the directory by deleting files from it.
(d) Use FailedPrecondition if the client performs conditional
    REST Get/Update/Delete on a resource and the resource on the
    server does not match the condition. E.g., conflicting
    read-modify-write on the same resource.

This error code will not be generated by the gRPC framework.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewHttpResponseEncodeWriter

func NewHttpResponseEncodeWriter(w http.ResponseWriter, opts ...ResponseWriterOption) func(error) *httpResponseEncoder

NewHttpResponseEncodeWriter returns a function which is used to write a gRPC error to a http.ResponseWriter using an encoding such as JSON.

Example
w := httptest.NewRecorder()
encodeAndWrite := NewHttpResponseEncodeWriter(w)

unimplementedGRPCError := NewUnimplemented("")

if err := encodeAndWrite(unimplementedGRPCError).AsJSON(); err != nil {
	panic(err)
}

result := w.Result()
defer result.Body.Close()
httpResponseBody, err := ioutil.ReadAll(result.Body)
if err != nil {
	panic(err)
}

fmt.Printf("\nHTTP Status code: %d\n", result.StatusCode)
fmt.Printf("HTTP Body:\n%s\n", string(httpResponseBody))
Output:

func NewInternal

func NewInternal(errMsg string, debugInfo *DebugInfo) (error, error)

NewInternal construct a gRPC error that means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken.

This error code will be generated by the gRPC framework in several internal error conditions.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewInvalidArgument

func NewInvalidArgument(errMsg string, fieldViolations []FieldViolation) (error, error)

NewInvalidArgument constructs a gRPC error that indicates the client specified an invalid argument. Note that this differs from FailedPrecondition. It indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).

This error code will not be generated by the gRPC framework.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewNotFound

func NewNotFound(errMsg string, resourceInfo *ResourceInfo) (error, error)

NewNotFound constructs a gRPC error that means some requested entity (e.g., file or directory) was not found.

This error code will not be generated by the gRPC framework.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewOutOfRange

func NewOutOfRange(errMsg string, fieldViolations []FieldViolation) (error, error)

NewOutOfRange constructs a gRPC error that means the operation was attempted past the valid range. E.g., seeking or reading past end of file.

Unlike InvalidArgument, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate InvalidArgument if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OutOfRange if asked to read from an offset past the current file size.

There is a fair bit of overlap between FailedPrecondition and OutOfRange. We recommend using OutOfRange (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OutOfRange error to detect when they are done.

This error code will not be generated by the gRPC framework.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewPermissionDenied

func NewPermissionDenied(errMsg string, errorInfo *ErrorInfo) (error, error)

NewPermissionDenied constructs a gRPC error that indicates the caller does not have permission to execute the specified operation. It must not be used for rejections caused by exhausting some resource (use ResourceExhausted instead for those errors). It must not be used if the caller cannot be identified (use Unauthenticated instead for those errors).

This error code will not be generated by the gRPC core framework, but expect authentication middleware to use it.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewResourceExhausted

func NewResourceExhausted(errMsg string, quotaViolations []QuotaViolation) (error, error)

NewResourceExhausted constructs a gRPC error that indicates some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.

This error code will be generated by the gRPC framework in out-of-memory and server overload situations, or when a message is larger than the configured maximum size.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewUnauthenticated

func NewUnauthenticated(errMsg string, errorInfo *ErrorInfo) (error, error)

NewUnauthenticated constructs a gRPC error that indicates the request does not have valid authentication credentials for the operation.

The gRPC framework will generate this error code when the authentication metadata is invalid or a Credentials callback fails, but also expect authentication middleware to generate it.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewUnavailable

func NewUnavailable(errMsg string, debugInfo *DebugInfo) (error, error)

NewUnavailable constructs a gRPC error that indicates the service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.

See litmus test above for deciding between FailedPrecondition, Aborted, and Unavailable.

This error code will be generated by the gRPC framework during abrupt shutdown of a server process or network connection.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewUnimplemented

func NewUnimplemented(errMsg string) error

NewUnimplemented constructs a gRPC error that indicates operation is not implemented or not supported/enabled in this service.

This error code will be generated by the gRPC framework. Most commonly, you will see this error code when a method implementation is missing on the server. It can also be generated for unknown compression algorithms or a disagreement as to whether an RPC should be streaming.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

func NewUnknown

func NewUnknown(errMsg string, debugInfo *DebugInfo) (error, error)

NewUnknown constructs a gRPC error that means an unknown error has occured. An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.

The gRPC framework will generate this error code in the above two mentioned cases.

Source: https://github.com/grpc/grpc-go/blob/master/codes/codes.go

Types

type DebugInfo

type DebugInfo struct {
	// The stack trace entries indicating where the error occurred.
	StackEntries []string
	// Additional debugging information provided by the server.
	Detail string
}

Describes additional debugging info.

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func DebugInfoFrom

func DebugInfoFrom(gRPCErr error) DebugInfo

DebugInfoFrom returns the DebugInfo from a gRPC error. If there isn't any, the zero value of DebugInfo is returned.

type ErrorInfo

type ErrorInfo struct {
	// The reason of the error. This is a constant value that identifies the
	// proximate cause of the error. Error reasons are unique within a particular
	// domain of errors. This should be at most 63 characters and match
	// /[A-Z0-9_]+/.
	Reason string
	// The logical grouping to which the "reason" belongs. The error domain
	// is typically the registered service name of the tool or product that
	// generates the error. Example: "pubsub.googleapis.com". If the error is
	// generated by some common infrastructure, the error domain must be a
	// globally unique value that identifies the infrastructure. For Google API
	// infrastructure, the error domain is "googleapis.com".
	Domain string
	// Additional structured details about this error.
	//
	// Keys should match /[a-zA-Z0-9-_]/ and be limited to 64 characters in
	// length. When identifying the current value of an exceeded limit, the units
	// should be contained in the key, not the value.  For example, rather than
	// {"instanceLimit": "100/request"}, should be returned as,
	// {"instanceLimitPerRequest": "100"}, if the client exceeds the number of
	// instances that can be created in a single (batch) request.
	Metadata map[string]string
}

Describes the cause of the error with structured details.

Example of an error when contacting the "pubsub.googleapis.com" API when it is not enabled:

{ "reason": "API_DISABLED"
  "domain": "googleapis.com"
  "metadata": {
    "resource": "projects/123",
    "service": "pubsub.googleapis.com"
  }
}

This response indicates that the pubsub.googleapis.com API is not enabled.

Example of an error that is returned when attempting to create a Spanner instance in a region that is out of stock:

{ "reason": "STOCKOUT"
  "domain": "spanner.googleapis.com",
  "metadata": {
    "availableRegions": "us-central1,us-east2"
  }
}

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func ErrorInfoFrom

func ErrorInfoFrom(gRPCErr error) ErrorInfo

ErrorInfoFrom returns the ErrorInfo from a gRPC error. If there isn't any, the zero value of ErrorInfo is returned.

type FieldViolation

type FieldViolation struct {
	// A path leading to a field in the request body. The value will be a
	// sequence of dot-separated identifiers that identify a protocol buffer
	// field. E.g., "field_violations.field" would identify this field.
	Field string
	// A description of why the request element is bad.
	Description string
}

A message type used to describe a single bad request field.

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func FieldViolationsFrom

func FieldViolationsFrom(gRPCErr error) []FieldViolation

FieldViolationsFrom returns the slice of FieldViolations from a gRPC error. If there isn't any, an empty slice is returned.

type HelpLink struct {
	// Describes what the link offers.
	Description string
	// URL pointing to additional information on handling the current error.
	URL string
}

Provides a link to documentation or for performing an out of band action.

For example, if a quota check failed with an error indicating the calling project hasn't enabled the accessed service, this can contain a URL pointing directly to the right place in the developer console to flip the bit.

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func HelpLinksFrom

func HelpLinksFrom(gRPCErr error) []HelpLink

HelpLinksFrom returns the slice of HelpLinks from a gRPC error. If there isn't any, an empty slice is returned.

type LocalizedMessage

type LocalizedMessage struct {
	// The locale used following the specification defined at
	// http://www.rfc-editor.org/rfc/bcp/bcp47.txt.
	// Examples are: "en-US", "fr-CH", "es-MX"
	Locale string
	// The localized error message in the above locale.
	Message string
}

Provides a localized error message that is safe to return to the user which can be attached to an RPC error.

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func LocalizedMessageFrom

func LocalizedMessageFrom(gRPCErr error) LocalizedMessage

LocalizedMessageFrom returns the LocalizedMessage from a gRPC error. If there isn't any, the zero value of LocalizedMessage is returned.

type PreconditionFailure

type PreconditionFailure struct {
	// The type of PreconditionFailure. We recommend using a service-specific
	// enum type to define the supported precondition violation subjects. For
	// example, "TOS" for "Terms of Service violation".
	Type string
	// The subject, relative to the type, that failed.
	// For example, "google.com/cloud" relative to the "TOS" type would indicate
	// which terms of service is being referenced.
	Subject string
	// A description of how the precondition failed. Developers can use this
	// description to understand how to fix the failure.
	//
	// For example: "Terms of service not accepted".
	Description string
}

A message type used to describe a single precondition failure.

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func PreconditionFailuresFrom

func PreconditionFailuresFrom(gRPCErr error) []PreconditionFailure

PreconditionFailuresFrom returns the slice of PreconditionFailures from a gRPC error. If there isn't any, an empty slice is returned.

type QuotaViolation

type QuotaViolation struct {
	// The subject on which the quota check failed.
	// For example, "clientip:<ip address of client>" or "project:<Google
	// developer project id>".
	Subject string
	// A description of how the quota check failed. Clients can use this
	// description to find more about the quota configuration in the service's
	// public documentation, or find the relevant quota limit to adjust through
	// developer console.
	//
	// For example: "Service disabled" or "Daily Limit for read operations
	// exceeded".
	Description string
}

A message type used to describe a single quota violation. For example, a daily quota or a custom quota that was exceeded.

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func QuotaViolationsFrom

func QuotaViolationsFrom(gRPCErr error) []QuotaViolation

QuotaViolationsFrom returns the slice of QuotaViolations from a gRPC error. If there isn't any, an empty slice is returned.

type RequestInfo

type RequestInfo struct {
	// An opaque string that should only be interpreted by the service generating
	// it. For example, it can be used to identify requests in the service's logs.
	RequestID string
	// Any data that was used to serve this request. For example, an encrypted
	// stack trace that can be sent back to the service provider for debugging.
	ServingData string
}

Contains metadata about the request that clients can attach when filing a bug or providing other forms of feedback.

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func RequestInfoFrom

func RequestInfoFrom(gRPCErr error) RequestInfo

RequestInfoFrom returns the RequestInfo from a gRPC error. If there's no RequestInfo details,the zero value of RequestInfo is returned.

type ResourceInfo

type ResourceInfo struct {
	// A name for the type of resource being accessed, e.g. "sql table",
	// "cloud storage bucket", "file", "Google calendar"; or the type URL
	// of the resource: e.g. "type.googleapis.com/google.pubsub.v1.Topic".
	ResourceType string
	// The name of the resource being accessed.  For example, a shared calendar
	// name: "example.com_4fghdhgsrgh@group.calendar.google.com", if the current
	// error is [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED].
	ResourceName string
	// The owner of the resource (optional).
	// For example, "user:<owner email>" or "project:<Google developer project
	// id>".
	Owner string
	// Describes what error is encountered when accessing this resource.
	// For example, updating a cloud project may require the `writer` permission
	// on the developer console project.
	Description string
}

Describes the resource that is being accessed.

Source: https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails

func ResourceInfoFrom

func ResourceInfoFrom(gRPCErr error) ResourceInfo

ResourceInfoFrom returns the ResourceInfo from a gRPC error. If there isn't any, the zero value of ResourceInfo is returned.

type ResponseWriterOption

type ResponseWriterOption func(w http.ResponseWriter)

ResponseWriterOption is an option function used to modify its http.ResponseWriter argument. For example, to set additional header values or to modify existing ones.

Jump to

Keyboard shortcuts

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