vterrors

package
v0.14.1 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2022 License: Apache-2.0, BSD-2-Clause Imports: 12 Imported by: 123

Documentation

Overview

Package vterrors provides simple error handling primitives for Vitess

In all Vitess code, errors should be propagated using vterrors.Wrapf() and not fmt.Errorf(). This makes sure that stacktraces are kept and propagated correctly.

New errors should be created using vterrors.New or vterrors.Errorf

Vitess uses canonical error codes for error reporting. This is based on years of industry experience with error reporting. This idea is that errors should be classified into a small set of errors (10 or so) with very specific meaning. Each error has a code, and a message. When errors are passed around (even through RPCs), the code is propagated. To handle errors, only the code should be looked at (and not string-matching on the error message).

Error codes are defined in /proto/vtrpc.proto. Along with an RPCError message that can be used to transmit errors through RPCs, in the message payloads. These codes match the names and numbers defined by gRPC.

A standardized error implementation that allows you to build an error with an associated canonical code is also defined. While sending an error through gRPC, these codes are transmitted using gRPC's error propagation mechanism and decoded back to the original code on the other end.

Retrieving the cause of an error

Using vterrors.Wrap constructs a stack of errors, adding context to the preceding error, instead of simply building up a string. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface

type causer interface {
        Cause() error
}

can be inspected by vterrors.Cause and vterrors.RootCause.

  • vterrors.Cause will find the immediate cause if one is available, or nil if the error is not a `causer` or if no cause is available.

  • vterrors.RootCause will recursively retrieve the topmost error which does not implement causer, which is assumed to be the original cause. For example:

    switch err := errors.RootCause(err).(type) { case *MyError: // handle specifically default: // unknown error }

causer interface is not exported by this package, but is considered a part of stable public API.

Formatted printing of errors

All error values returned from this package implement fmt.Formatter and can be formatted by the fmt package. The following verbs are supported

%s    print the error. If the error has a Cause it will be
      printed recursively
%v    extended format. Each Frame of the error's StackTrace will
      be printed in detail.

Most but not all of the code in this file was originally copied from https://github.com/pkg/errors/blob/v0.8.0/errors.go

Index

Constants

View Source
const (
	// Informational errors.
	PriorityOK = iota
	PriorityCanceled
	PriorityAlreadyExists
	PriorityOutOfRange
	// Potentially retryable errors.
	PriorityUnavailable
	PriorityDeadlineExceeded
	PriorityAborted
	PriorityFailedPrecondition
	PriorityClusterEvent
	// Permanent errors.
	PriorityResourceExhausted
	PriorityUnknown
	PriorityUnauthenticated
	PriorityPermissionDenied
	PriorityInvalidArgument
	PriorityNotFound
	PriorityUnimplemented
	// Serious errors.
	PriorityInternal
	PriorityDataLoss
)

A list of all vtrpcpb.Code, ordered by priority. These priorities are used when aggregating multiple errors in VtGate. Higher priority error codes are more urgent for users to see. They are prioritized based on the following question: assuming a scatter query produced multiple errors, which of the errors is the most likely to give the user useful information about why the query failed and how they should proceed?

View Source
const (
	NotServing   = "operation not allowed in state NOT_SERVING"
	ShuttingDown = "operation not allowed in state SHUTTING_DOWN"
)

Operation not allowed error

View Source
const (
	// PrimaryVindexNotSet is the error message to be used when there is no primary vindex found on a table
	PrimaryVindexNotSet = "table '%s' does not have a primary vindex"
)

Constants for error messages

View Source
const TxEngineClosed = "tx engine can't accept new connections in state %v"

TxEngineClosed for transaction engine closed error

View Source
const TxKillerRollback = "in use: for tx killer rollback"

TxKillerRollback purpose when acquire lock on connection for rolling back transaction.

View Source
const WrongTablet = "wrong tablet type"

WrongTablet for invalid tablet type error

Variables

View Source
var LogErrStacks bool

LogErrStacks controls whether or not printing errors includes the embedded stack trace in the output.

View Source
var RxOp = regexp.MustCompile("operation not allowed in state (NOT_SERVING|SHUTTING_DOWN)")

RxOp regex for operation not allowed error

View Source
var RxWrongTablet = regexp.MustCompile("(wrong|invalid) tablet type")

RxWrongTablet regex for invalid tablet type error

View Source
var TxClosed = regexp.MustCompile("transaction ([a-z0-9:]+) (?:ended|not found|in use: for tx killer rollback)")

TxClosed regex for connection closed

Functions

func Aggregate

func Aggregate(errors []error) error

Aggregate aggregates several errors into a single one. The resulting error code will be the one with the highest priority as defined by the priority constants in this package.

func Cause

func Cause(err error) error

Cause will return the immediate cause, if possible. An error value has a cause if it implements the following interface:

type causer interface {
       Cause() error
}

If the error does not implement Cause, nil will be returned

func Code

func Code(err error) vtrpcpb.Code

Code returns the error code if it's a vtError. If err is nil, it returns ok.

func Equals

func Equals(a, b error) bool

Equals returns true iff the error message and the code returned by Code() are equal.

func Errorf

func Errorf(code vtrpcpb.Code, format string, args ...any) error

Errorf formats according to a format specifier and returns the string as a value that satisfies error. Errorf also records the stack trace at the point it was called.

func FromGRPC

func FromGRPC(err error) error

FromGRPC returns a gRPC error as a vtError, translating between error codes. However, there are a few errors which are not translated and passed as they are. For example, io.EOF since our code base checks for this error to find out that a stream has finished.

func FromVTRPC

func FromVTRPC(rpcErr *vtrpcpb.RPCError) error

FromVTRPC recovers a vtError from a *vtrpcpb.RPCError (which is how vtError is transmitted across proto3 RPC boundaries).

func New

func New(code vtrpcpb.Code, message string) error

New returns an error with the supplied message. New also records the stack trace at the point it was called.

func NewErrorf added in v0.10.0

func NewErrorf(code vtrpcpb.Code, state State, format string, args ...any) error

NewErrorf formats according to a format specifier and returns the string as a value that satisfies error. NewErrorf also records the stack trace at the point it was called.

func Print

func Print(err error) string

Print is meant to print the vtError object in test failures. For comparing two vterrors, use Equals() instead.

func RootCause

func RootCause(err error) error

RootCause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:

type causer interface {
       Cause() error
}

If the error does not implement Cause, the original error will be returned. If the error is nil, nil will be returned without further investigation.

func ToGRPC

func ToGRPC(err error) error

ToGRPC returns an error as a gRPC error, with the appropriate error code.

func ToVTRPC

func ToVTRPC(err error) *vtrpcpb.RPCError

ToVTRPC converts from vtError to a vtrpcpb.RPCError.

func Wrap

func Wrap(err error, message string) error

Wrap returns an error annotating err with a stack trace at the point Wrap is called, and the supplied message. If err is nil, Wrap returns nil.

func Wrapf

func Wrapf(err error, format string, args ...any) error

Wrapf returns an error annotating err with a stack trace at the point Wrapf is call, and the format specifier. If err is nil, Wrapf returns nil.

Types

type Frame

type Frame uintptr

Frame represents a program counter inside a stack frame.

func (Frame) Format

func (f Frame) Format(s fmt.State, verb rune)

Format formats the frame according to the fmt.Formatter interface.

%s    source file
%d    source line
%n    function name
%v    equivalent to %s:%d

Format accepts flags that alter the printing of some verbs, as follows:

%+s   path of source file relative to the compile time GOPATH
%+v   equivalent to %+s:%d

type StackTrace

type StackTrace []Frame

StackTrace is stack of Frames from innermost (newest) to outermost (oldest).

func (StackTrace) Format

func (st StackTrace) Format(s fmt.State, verb rune)

Format format the stacktrace according to the fmt.Formatter interface.

%s    source file
%d    source line
%n    function name
%v    equivalent to %s:%d

Format accepts flags that alter the printing of some verbs, as follows:

%+s   path of source file relative to the compile time GOPATH
%+v   equivalent to %+s:%d

type State added in v0.10.0

type State int

State is error state

const (
	Undefined State = iota

	// invalid argument
	BadFieldError
	BadTableError
	CantUseOptionHere
	DataOutOfRange
	EmptyQuery
	ForbidSchemaChange
	IncorrectGlobalLocalVar
	NonUniqError
	NonUniqTable
	NonUpdateableTable
	SyntaxError
	WrongFieldWithGroup
	WrongGroupField
	WrongTypeForVar
	WrongValueForVar
	LockOrActiveTransaction
	MixOfGroupFuncAndFields
	DupFieldName
	WrongValueCountOnRow

	// failed precondition
	NoDB
	InnodbReadOnly
	WrongNumberOfColumnsInSelect
	CantDoThisInTransaction
	RequiresPrimaryKey
	OperandColumns

	// not found
	BadDb
	DbDropExists
	NoSuchTable
	SPDoesNotExist
	UnknownSystemVariable
	UnknownTable
	NoSuchSession

	// already exists
	DbCreateExists

	// resource exhausted
	NetPacketTooLarge

	// cancelled
	QueryInterrupted

	// unimplemented
	NotSupportedYet
	UnsupportedPS

	// permission denied
	AccessDeniedError

	// server not available
	ServerNotAvailable

	// No state should be added below NumOfStates
	NumOfStates
)

All the error states

func ErrState added in v0.10.0

func ErrState(err error) State

ErrState returns the error state if it's a vtError. If err is nil, it returns Undefined.

Jump to

Keyboard shortcuts

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