sql_parser_errors

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package sql_parser_errors provides simple error handling primitives

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

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

This is 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 sql_parser_errors.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 sql_parser_errors.Cause and sql_parser_errors.RootCause.

  • sql_parser_errors.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.

  • sql_parser_errors.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 (
	// OK is returned on success.
	Code_OK int32 = 0
	// CANCELED indicates the operation was cancelled (typically by the caller).
	Code_CANCELED int32 = 1
	// UNKNOWN error. 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.
	Code_UNKNOWN int32 = 2
	// INVALID_ARGUMENT indicates client specified an invalid argument.
	// Note that this differs from FAILED_PRECONDITION. It indicates arguments
	// that are problematic regardless of the state of the system
	// (e.g., a malformed file name).
	Code_INVALID_ARGUMENT int32 = 3
	// DEADLINE_EXCEEDED 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.
	Code_DEADLINE_EXCEEDED int32 = 4
	// NOT_FOUND means some requested entity (e.g., file or directory) was
	// not found.
	Code_NOT_FOUND int32 = 5
	// ALREADY_EXISTS means an attempt to create an entity failed because one
	// already exists.
	Code_ALREADY_EXISTS int32 = 6
	// PERMISSION_DENIED 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 RESOURCE_EXHAUSTED
	// instead for those errors).  It must not be
	// used if the caller cannot be identified (use Unauthenticated
	// instead for those errors).
	Code_PERMISSION_DENIED int32 = 7
	// RESOURCE_EXHAUSTED indicates some resource has been exhausted, perhaps
	// a per-user quota, or perhaps the entire file system is out of space.
	Code_RESOURCE_EXHAUSTED int32 = 8
	// FAILED_PRECONDITION 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 FAILED_PRECONDITION, 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 FAILED_PRECONDITION 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, FAILED_PRECONDITION
	//      should be returned since the client should not retry unless
	//      they have first fixed up the directory by deleting files from it.
	//  (d) Use FAILED_PRECONDITION 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.
	Code_FAILED_PRECONDITION int32 = 9
	// ABORTED 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 FAILED_PRECONDITION,
	// ABORTED, and UNAVAILABLE.
	Code_ABORTED int32 = 10
	// OUT_OF_RANGE means operation was attempted past the valid range.
	// E.g., seeking or reading past end of file.
	//
	// Unlike INVALID_ARGUMENT, this error indicates a problem that may
	// be fixed if the system state changes. For example, a 32-bit file
	// system will generate INVALID_ARGUMENT if asked to read at an
	// offset that is not in the range [0,2^32-1], but it will generate
	// OUT_OF_RANGE if asked to read from an offset past the current
	// file size.
	//
	// There is a fair bit of overlap between FAILED_PRECONDITION and
	// OUT_OF_RANGE.  We recommend using OUT_OF_RANGE (the more specific
	// error) when it applies so that callers who are iterating through
	// a space can easily look for an OUT_OF_RANGE error to detect when
	// they are done.
	Code_OUT_OF_RANGE int32 = 11
	// UNIMPLEMENTED indicates operation is not implemented or not
	// supported/enabled in this service.
	Code_UNIMPLEMENTED int32 = 12
	// INTERNAL errors. Means some invariants expected by underlying
	// system has been broken.  If you see one of these errors,
	// something is very broken.
	Code_INTERNAL int32 = 13
	// UNAVAILABLE indicates the service is currently unavailable.
	// This is a most likely a transient condition and may be corrected
	// by retrying with a backoff.
	//
	// See litmus test above for deciding between FAILED_PRECONDITION,
	// ABORTED, and UNAVAILABLE.
	Code_UNAVAILABLE int32 = 14
	// DATA_LOSS indicates unrecoverable data loss or corruption.
	Code_DATA_LOSS int32 = 15
	// UNAUTHENTICATED indicates the request does not have valid
	// authentication credentials for the operation.
	Code_UNAUTHENTICATED int32 = 16
	// CLUSTER_EVENT indicates that a cluster operation might be in effect
	Code_CLUSTER_EVENT int32 = 17
	// Topo server connection is read-only
	Code_READ_ONLY int32 = 18
)
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 (
	Code_name = map[int32]string{
		0:  "OK",
		1:  "CANCELED",
		2:  "UNKNOWN",
		3:  "INVALID_ARGUMENT",
		4:  "DEADLINE_EXCEEDED",
		5:  "NOT_FOUND",
		6:  "ALREADY_EXISTS",
		7:  "PERMISSION_DENIED",
		8:  "RESOURCE_EXHAUSTED",
		9:  "FAILED_PRECONDITION",
		10: "ABORTED",
		11: "OUT_OF_RANGE",
		12: "UNIMPLEMENTED",
		13: "INTERNAL",
		14: "UNAVAILABLE",
		15: "DATA_LOSS",
		16: "UNAUTHENTICATED",
		17: "CLUSTER_EVENT",
		18: "READ_ONLY",
	}
	Code_value = map[string]int32{
		"OK":                  0,
		"CANCELED":            1,
		"UNKNOWN":             2,
		"INVALID_ARGUMENT":    3,
		"DEADLINE_EXCEEDED":   4,
		"NOT_FOUND":           5,
		"ALREADY_EXISTS":      6,
		"PERMISSION_DENIED":   7,
		"RESOURCE_EXHAUSTED":  8,
		"FAILED_PRECONDITION": 9,
		"ABORTED":             10,
		"OUT_OF_RANGE":        11,
		"UNIMPLEMENTED":       12,
		"INTERNAL":            13,
		"UNAVAILABLE":         14,
		"DATA_LOSS":           15,
		"UNAUTHENTICATED":     16,
		"CLUSTER_EVENT":       17,
		"READ_ONLY":           18,
	}
)

Enum value maps for Code.

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 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) int32

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 int32, 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 NewError

func NewError(code int32, message string) error

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

func NewErrorf

func NewErrorf(code int32, 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 sql_parser_errors, 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 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

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

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