errors

package
v3.32.1 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2024 License: Apache-2.0 Imports: 28 Imported by: 11

Documentation

Overview

Package errors implements rich errors that carry contextual information such as stack traces, causality and attributes.

Example
package main

import (
	"fmt"

	"go.thethings.network/lorawan-stack/v3/pkg/errors"
	"go.thethings.network/lorawan-stack/v3/pkg/ttnpb"
)

func main() {
	errApplicationNotFound := errors.DefineNotFound(
		"application_not_found",
		"Application with ID `{id}` not found",
	// Public attribute "id" is parsed from the message format.
	)
	errCouldNotCreateDevice := errors.Define(
		"could_not_create_device",
		"Could not create Device",
		"right_answer", // right_answer could be some extra attribute (that isn't rendered in the message format)
	)

	findApplication := func(id *ttnpb.ApplicationIdentifiers) (*ttnpb.Application, error) {
		// try really hard, but fail
		return nil, errApplicationNotFound.WithAttributes("id", id.GetApplicationId())
	}

	createDevice := func(dev *ttnpb.EndDevice) error {
		app, err := findApplication(dev.Ids.ApplicationIds)
		if err != nil {
			return err // you can just pass errors up
		}
		// create device
		_ = app
		return nil
	}

	if err := createDevice(&ttnpb.EndDevice{Ids: &ttnpb.EndDeviceIdentifiers{}}); err != nil {
		fmt.Println(errCouldNotCreateDevice.WithCause(err).WithAttributes("right_answer", 42))
	}

}
Output:

error:pkg/errors_test:could_not_create_device (Could not create Device)

Index

Examples

Constants

This section is empty.

Variables

View Source
var (

	// ErrContextCanceled is the Definition of the standard context.Cancelled error.
	// This variant exists in order to allow the error code to be properly propagated
	// over gRPC calls, otherwise the error code is unknown.
	ErrContextCanceled = DefineCanceled("context_canceled", "context canceled")
	// ErrContextDeadlineExceeded is the definition of the standard context.DeadlineExceeded error.
	// This variant exists in order to allow the error code to be properly propagated
	// over gRPC calls, otherwise the error code is unknown.
	ErrContextDeadlineExceeded = DefineDeadlineExceeded(
		"context_deadline_exceeded", "context deadline exceeded",
	)
)
View Source
var (
	As     = errors.As
	Is     = errors.Is
	Unwrap = errors.Unwrap
)

Alias standard library error functions.

View Source
var ErrorDetailsFromProto func(msg ...proto.Message) (details ErrorDetails, rest []proto.Message)

ErrorDetailsFromProto ranges over the given protobuf-encoded messages to extract the ErrorDetails. It returns details if present, as well as the rest of the details.

This variable is set by pkg/ttnpb.

View Source
var ErrorDetailsToProto func(e ErrorDetails) (msg proto.Message)

ErrorDetailsToProto converts the given ErrorDetails into a protobuf-encoded message.

This variable is set by pkg/ttnpb.

View Source
var JSONCodec interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
} = jsonpb.TTN()

JSONCodec can be used to override the jsonpb codec.

Functions

func Attributes

func Attributes(err ...error) map[string]any

Attributes returns the attributes of the errors, if they implement Attributes(). If more than one error is passed, subsequent error attributes will be added if not set.

func Cause

func Cause(err error) error

Cause returns the cause of the given error, if any.

func Code

func Code(err error) uint32

Code gets the code of an error. If the error doesn't implement codes, Unknown is returned.

func Details

func Details(err error) []proto.Message

Details gets the details of the error.

func FromHTTP

func FromHTTP(resp *http.Response) error

FromHTTP reads an error from the HTTP response.

func GenerateCorrelationIDs added in v3.14.2

func GenerateCorrelationIDs(enable bool)

GenerateCorrelationIDs configures whether random correlation IDs are generated for each error. This is enabled by default.

func HasCode

func HasCode(err error, c uint32) bool

HasCode returns whether the given error has the given error code. If the error doesn't implement codes, it doesn't have any code.

func IsAborted

func IsAborted(err error) bool

IsAborted returns whether the given error is of type Aborted.

func IsAlreadyExists

func IsAlreadyExists(err error) bool

IsAlreadyExists returns whether the given error is of type AlreadyExists.

func IsCanceled

func IsCanceled(err error) bool

IsCanceled returns whether the givenerror is context.Canceled or of type Canceled.

func IsDataLoss

func IsDataLoss(err error) bool

IsDataLoss returns whether the given error is of type DataLoss.

func IsDeadlineExceeded

func IsDeadlineExceeded(err error) bool

IsDeadlineExceeded returns whether the givenerror is context.DeadlineExceeded or of type DeadlineExceeded.

func IsFailedPrecondition

func IsFailedPrecondition(err error) bool

IsFailedPrecondition returns whether the given error is of type FailedPrecondition.

func IsInternal

func IsInternal(err error) bool

IsInternal returns whether the given error is of type Internal.

func IsInvalidArgument

func IsInvalidArgument(err error) bool

IsInvalidArgument returns whether the given error is of type InvalidArgument.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns whether the given error is of type NotFound.

func IsPermissionDenied

func IsPermissionDenied(err error) bool

IsPermissionDenied returns whether the given error is of type PermissionDenied.

func IsResourceExhausted

func IsResourceExhausted(err error) bool

IsResourceExhausted returns whether the given error is of type ResourceExhausted.

func IsUnauthenticated

func IsUnauthenticated(err error) bool

IsUnauthenticated returns whether the given error is of type Unauthenticated.

func IsUnavailable

func IsUnavailable(err error) bool

IsUnavailable returns whether the given error is of type Unavailable.

func IsUnimplemented added in v3.9.0

func IsUnimplemented(err error) bool

IsUnimplemented returns whether the given error is of type Unimplemented.

func IsUnknown

func IsUnknown(err error) bool

IsUnknown returns whether the given error is of type Unknown.

func PublicAttributes

func PublicAttributes(err ...error) map[string]any

PublicAttributes returns the public attributes of the errors, if they implement PublicAttributes(). If more than one error is passed, subsequent error attributes will be added if not set.

func Resemble

func Resemble(a, b error) bool

Resemble returns true iff the given errors resemble, meaning that the Namespace and Name of the errors are equal. A nil error only resembles nil. Invalid errors or definitions (including typed nil) never resemble anything.

func RootCause

func RootCause(err error) error

RootCause walks up the "error chain" until it finds the root cause of an error.

func Stack

func Stack(err error) (stack []error)

Stack returns the entire error stack, including the given error.

func StreamClientInterceptor

func StreamClientInterceptor() grpc.StreamClientInterceptor

StreamClientInterceptor converts gRPC errors to regular errors.

func StreamServerInterceptor

func StreamServerInterceptor() grpc.StreamServerInterceptor

StreamServerInterceptor makes sure that returned TTN errors contain a CorrelationID.

func ToHTTP

func ToHTTP(in error, w http.ResponseWriter) error

ToHTTP writes the error to the HTTP response.

func ToHTTPStatusCode

func ToHTTPStatusCode(err error) int

ToHTTPStatusCode maps an error to HTTP response codes.

func UnaryClientInterceptor

func UnaryClientInterceptor() grpc.UnaryClientInterceptor

UnaryClientInterceptor converts gRPC errors to regular errors.

func UnaryServerInterceptor

func UnaryServerInterceptor() grpc.UnaryServerInterceptor

UnaryServerInterceptor makes sure that returned TTN errors contain a CorrelationID.

Types

type Definition

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

Definition of a registered error.

func Define

func Define(name, messageFormat string, publicAttributes ...string) *Definition

Define defines a registered error of type Unknown.

func DefineAborted

func DefineAborted(name, messageFormat string, publicAttributes ...string) *Definition

DefineAborted defines a registered error of type Aborted.

func DefineAlreadyExists

func DefineAlreadyExists(name, messageFormat string, publicAttributes ...string) *Definition

DefineAlreadyExists defines a registered error of type AlreadyExists.

func DefineCanceled added in v3.8.2

func DefineCanceled(name, messageFormat string, publicAttributes ...string) *Definition

DefineCanceled defines a registered error of type Canceled.

func DefineCorruption

func DefineCorruption(name, messageFormat string, publicAttributes ...string) *Definition

DefineCorruption is the same as DefineDataLoss.

func DefineDataLoss

func DefineDataLoss(name, messageFormat string, publicAttributes ...string) *Definition

DefineDataLoss defines a registered error of type DataLoss.

func DefineDeadlineExceeded added in v3.8.2

func DefineDeadlineExceeded(name, messageFormat string, publicAttributes ...string) *Definition

DefineDeadlineExceeded defines a registered error of type DeadlineExceeded.

func DefineFailedPrecondition

func DefineFailedPrecondition(name, messageFormat string, publicAttributes ...string) *Definition

DefineFailedPrecondition defines a registered error of type FailedPrecondition. Use Unavailable if the client can retry just the failing call. Use Aborted if the client should retry at a higher-level.

func DefineInternal

func DefineInternal(name, messageFormat string, publicAttributes ...string) *Definition

DefineInternal defines a registered error of type Internal.

func DefineInvalidArgument

func DefineInvalidArgument(name, messageFormat string, publicAttributes ...string) *Definition

DefineInvalidArgument defines a registered error of type InvalidArgument.

func DefineNotFound

func DefineNotFound(name, messageFormat string, publicAttributes ...string) *Definition

DefineNotFound defines a registered error of type NotFound.

func DefinePermissionDenied

func DefinePermissionDenied(name, messageFormat string, publicAttributes ...string) *Definition

DefinePermissionDenied defines a registered error of type PermissionDenied.

It should be used when a client attempts to perform an authorized action using incorrect credentials or credentials with insufficient rights. If the client attempts to perform the action without providing any form of authentication, Unauthenticated should be used instead.

func DefineResourceExhausted

func DefineResourceExhausted(name, messageFormat string, publicAttributes ...string) *Definition

DefineResourceExhausted defines a registered error of type ResourceExhausted.

func DefineUnauthenticated

func DefineUnauthenticated(name, messageFormat string, publicAttributes ...string) *Definition

DefineUnauthenticated defines a registered error of type Unauthenticated. It should be used when a client attempts to perform an authenticated action without providing any form of authentication. If the client attempts to perform the action using incorrect credentials or credentials with insufficient rights, PermissionDenied should be used instead.

func DefineUnavailable

func DefineUnavailable(name, messageFormat string, publicAttributes ...string) *Definition

DefineUnavailable defines a registered error of type Unavailable.

func DefineUnimplemented

func DefineUnimplemented(name, messageFormat string, publicAttributes ...string) *Definition

DefineUnimplemented defines a registered error of type Unimplemented.

func (*Definition) Attributes

func (*Definition) Attributes() map[string]any

Attributes are not present in the error definition, so this just returns nil.

func (*Definition) Cause

func (*Definition) Cause() error

Cause returns ret root cause of the error, in this case the descriptor itself.

func (*Definition) Code

func (d *Definition) Code() uint32

Code of the error. This code is consistent with google.golang.org/genproto/googleapis/rpc/code and google.golang.org/grpc/codes.

func (*Definition) CorrelationID

func (*Definition) CorrelationID() string

CorrelationID is not present in the error definition, so this just returns an empty string.

func (*Definition) Details

func (*Definition) Details() []proto.Message

Details are not present in the error definition, so this just returns nil.

func (*Definition) Error

func (d *Definition) Error() string

Error implements the error interface.

func (*Definition) FormatMessage

func (d *Definition) FormatMessage(attributes map[string]any) string

FormatMessage formats the message using the given attributes.

func (*Definition) FullName

func (d *Definition) FullName() string

FullName returns the full name (namespace:name) of the error.

func (*Definition) GRPCStatus

func (d *Definition) GRPCStatus() *status.Status

GRPCStatus returns the Definition as a gRPC status message.

func (*Definition) Is added in v3.10.1

func (d *Definition) Is(target error) bool

Is makes the Definition implement error comparison.

func (*Definition) MarshalJSON

func (d *Definition) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Definition) MessageFormat

func (d *Definition) MessageFormat() string

MessageFormat of the error.

func (*Definition) Name

func (d *Definition) Name() string

Name of the error.

func (*Definition) Namespace

func (d *Definition) Namespace() string

Namespace of the error.

func (*Definition) New

func (d *Definition) New() *Error

New returns a new error from the definition. This is not required, but will add a stack trace for improved debugging.

func (*Definition) PublicAttributes

func (*Definition) PublicAttributes() map[string]any

PublicAttributes are not present in the error definition, so this just returns nil.

func (*Definition) String

func (d *Definition) String() string

func (*Definition) UnmarshalJSON

func (d *Definition) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

This func is purely implemented for consistency. In practice, you probably want to unmarshal into an *Error instead of a *Definition.

func (*Definition) Unwrap added in v3.10.1

func (*Definition) Unwrap() error

Unwrap makes the Definition implement error unwrapping.

func (*Definition) WithAttributes

func (d *Definition) WithAttributes(kv ...any) *Error

WithAttributes returns a new error from the definition, and sets the given attributes.

func (*Definition) WithCause

func (d *Definition) WithCause(cause error) *Error

WithCause returns a new error from the definition, and sets the cause of the error.

func (*Definition) WithDetails

func (d *Definition) WithDetails(details ...proto.Message) *Error

WithDetails returns a new error from the definition, and sets the given details.

type DefinitionInterface

type DefinitionInterface interface {
	error
	fmt.Stringer
	Namespace() string
	Name() string
	FullName() string
	MessageFormat() string
	Code() uint32
}

DefinitionInterface is the interface of an error definition.

type Error

type Error struct {
	*Definition
	// contains filtered or unexported fields
}

Error is a rich error implementation.

func From

func From(err error) (out *Error, ok bool)

From returns an *Error if it can be derived from the given input. For a nil error, false will be returned.

func FromGRPCStatus

func FromGRPCStatus(grpcStatus *status.Status) *Error

FromGRPCStatus converts the gRPC status message into an Error.

func FromHTTPStatusCode

func FromHTTPStatusCode(status int, publicAttributes ...string) *Error

FromHTTPStatusCode maps an HTTP response code to an error.

func New

func New(text string) *Error

New returns an error that formats as the given text. This way of creating errors should be avoided if possible.

func (*Error) Attributes

func (e *Error) Attributes() map[string]any

Attributes of the error.

func (*Error) Cause

func (e *Error) Cause() error

Cause returns the cause of the error.

func (*Error) Code

func (e *Error) Code() uint32

Code of the error. If the code is invalid or unknown, this tries to get the code from the cause of this error. This code is consistent with google.golang.org/genproto/googleapis/rpc/code and google.golang.org/grpc/codes.

func (*Error) CorrelationID

func (e *Error) CorrelationID() string

CorrelationID of the error.

func (*Error) Details

func (e *Error) Details() (details []proto.Message)

Details of the error. Usually structs from ttnpb or google.golang.org/genproto/googleapis/rpc/errdetails.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Fields

func (e *Error) Fields() map[string]any

Fields implements the log.Fielder interface.

func (*Error) GRPCStatus

func (e *Error) GRPCStatus() *status.Status

GRPCStatus converts the Error into a gRPC status message.

func (*Error) Is added in v3.10.1

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

Is makes the Error implement error comparison.

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Error) New added in v3.29.1

func (*Error) New()

New exists in order to prevent accidentally calling Definition.New(). If you are sure that you want to create a fresh error, use .Definition.New().

func (*Error) PublicAttributes

func (e *Error) PublicAttributes() map[string]any

PublicAttributes of the error.

func (Error) StackTrace

func (s Error) StackTrace() errors.StackTrace

StackTrace implements the errors.stackTracer interface.

func (*Error) String

func (e *Error) String() string

func (*Error) UnmarshalJSON

func (e *Error) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Error) Unwrap added in v3.10.1

func (e *Error) Unwrap() error

Unwrap makes the Error implement error unwrapping.

func (*Error) WithAttributes

func (e *Error) WithAttributes(kv ...any) *Error

WithAttributes returns the error with the given attributes set. Any conflicting attributes in the Error will be overwritten.

func (*Error) WithCause

func (e *Error) WithCause(cause error) *Error

WithCause returns the error with the given cause set. Overwriting an existing cause in the Error will cause a panic.

func (*Error) WithDetails

func (e *Error) WithDetails(details ...proto.Message) *Error

WithDetails returns the error with the given details set. This appends to any existing details in the Error.

type ErrorDetails

type ErrorDetails interface {
	Error() string
	Namespace() string
	Name() string
	MessageFormat() string
	PublicAttributes() map[string]any
	CorrelationID() string
	Cause() error
	Code() uint32
	Details() []proto.Message
}

ErrorDetails that can be carried over API.

type Interface

type Interface interface {
	DefinitionInterface
	Attributes() map[string]any
	Cause() error
	Details() (details []proto.Message)
}

Interface is the interface of an error.

Directories

Path Synopsis
Package sentry converts errors to Sentry events.
Package sentry converts errors to Sentry events.

Jump to

Keyboard shortcuts

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