errors

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2022 License: Apache-2.0 Imports: 10 Imported by: 0

README

错误码

功能

  1. 需要能打印错误堆栈信息

  2. 能支持不同格式的打印,如%+v,%v,%s

    • %s 打印展示给用户的错误信息
    • %v alias for %s
    • %-v 打印堆栈,错误码,展示给用户的信息,展示给研发的信息(最外层)
    • %+v 打印堆栈,错误码,展示给用户的信息,展示给研发的信息(所有)
    • %#-v json 格式
    • %#+v json 格式
  3. 能支持wrap/unWarp 功能,在已有的错误信息上追加其他错误信息。

  4. 错误应有Is方法

  5. 错误包应支持As函数

  6. 支持两种创建方式,格式化和非格式化

    即 errors.New 和 errors.Errorf

  7. 能通过错误来确定接口返回 status code

Code 设计

设计原则

  1. 应当方便定位问题和代码行
  2. 错误码包含错误级别,错误模块,具体错误信息

Code 格式

XXYYZZ, XX 代表服务,YY 代表模块, ZZ 代表错误码序号

error 类型

  • withStack, 封装原有的错误, 并添加调用栈信息。支持 %v 格式化打印调用栈信息。 主要用于debug 信息。 不建议将此错误打印到除Debug level 以外的日志中。
  • withMessage, 包含withStack。 支持 %s 和 %v 格式化。 %s 将只打印错误信息。%v 将包含调用栈。
  • withCode, 包含 withMessage。 可以用%s 记录日志。 %v 打印调用栈, withCode 打印的调用栈相对上面的两个error 会相对简单,只显示一层, 可以打印到日志中去,方便分析。同时多层withCode 会递归打印每个withCode 的调用位置。withCode error 可以获得一个coder 来打印用户友好的错误信息。方便返回到api 中。

错误信息规范说明

  • 对外暴露的错误,统一大写开头,结尾不要加.。
  • 对外暴露的错误要简洁,并能准确说明问题。
  • 对外暴露的错误说明,应该是 该怎么做 而不是 哪里错了。

Documentation

Index

Constants

View Source
const (
	// ErrUnknown - 500: Internal server error.
	ErrUnknown = iota + 100000

	// ErrBind - 400: Error occurred while binding the request body to the struct.
	ErrBind

	// ErrValidation - 400: Validation failed.
	ErrValidation

	// ErrTokenInvalid - 401: Token invalid.
	ErrTokenInvalid

	// ErrPageNotFound - 404: Page not found.
	ErrPageNotFound
)
View Source
const (
	// ErrEncrypt - 401: Error occurred while encrypting the user password.
	ErrEncrypt int = iota + 100201

	// ErrSignatureInvalid - 401: Signature is invalid.
	ErrSignatureInvalid

	// ErrExpired - 401: Token expired.
	ErrExpired

	// ErrInvalidAuthHeader - 401: Invalid authorization header.
	ErrInvalidAuthHeader

	// ErrMissingHeader - 401: The `Authorization` header was empty.
	ErrMissingHeader

	// ErrPasswordIncorrect - 401: Password was incorrect.
	ErrPasswordIncorrect

	// ErrPermissionDenied - 403: Permission denied.
	ErrPermissionDenied
)

common: authorization and authentication errors.

View Source
const (
	// ErrEncodingFailed - 500: Encoding failed due to an error with the data.
	ErrEncodingFailed int = iota + 100301

	// ErrDecodingFailed - 500: Decoding failed due to an error with the data.
	ErrDecodingFailed

	// ErrInvalidJSON - 500: Data is not valid JSON.
	ErrInvalidJSON

	// ErrEncodingJSON - 500: JSON data could not be encoded.
	ErrEncodingJSON

	// ErrDecodingJSON - 500: JSON data could not be decoded.
	ErrDecodingJSON

	// ErrInvalidYaml - 500: Data is not valid Yaml.
	ErrInvalidYaml

	// ErrEncodingYaml - 500: Yaml data could not be encoded.
	ErrEncodingYaml

	// ErrDecodingYaml - 500: Yaml data could not be decoded.
	ErrDecodingYaml
)

common: encode/decode errors.

View Source
const (
	// ErrDatabase - 500: Database error.
	ErrDatabase int = iota + 100101
)

common: database errors.

Variables

This section is empty.

Functions

func Cause

func Cause(err error) error

Cause 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 Errorf

func Errorf(format string, args ...interface{}) 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 IsCode

func IsCode(err error, code int) bool

IsCode reports whether any error in err's chain contains the given error code.

func MustRegister

func MustRegister(coder Coder)

MustRegister register a user define error code. It will panic when the same Code already exist.

func New

func New(message string) error

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

func NewWithCode

func NewWithCode(code int, message string) error

func NewWithCodef

func NewWithCodef(code int, format string, args ...interface{}) error

func Register

func Register(coder Coder)

Register register a user define error code. It will overrid the exist code.

func WithCode

func WithCode(err error, code int, message string) error

func WithCodef

func WithCodef(err error, code int, format string, args ...interface{}) error

func WithMessage

func WithMessage(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 WithMessagef

func WithMessagef(err error, format string, args ...interface{}) error

WithMessagef annotates err with the format specifier. If err is nil, WithMessagef returns nil.

func WithStack

func WithStack(err error) error

WithStack annotates err with a stack trace at the point WithStack was called. If err is nil, WithStack returns nil.

Types

type Coder

type Coder interface {
	// HTTP status that should be used for the associated error code.
	HTTPStatus() int

	// External (user) facing error text.
	String() string

	// Reference returns the detail documents for user.
	Reference() string

	// Code returns the code of the coder
	Code() int
}

Coder defines an interface for an error code detail information.

func ParseCoder

func ParseCoder(err error) Coder

ParseCoder parse any error into *withCode. nil error will return nil direct. None withStack error will be parsed as ErrUnknown.

type DefaultCoder added in v1.3.1

type DefaultCoder struct {
	// C refers to the integer code of the ErrCode.
	C int

	// HTTP status that should be used for the associated error code.
	HTTP int

	// External (user) facing error text.
	Ext string

	// Ref specify the reference document.
	Ref string
}

func (DefaultCoder) Code added in v1.3.1

func (coder DefaultCoder) Code() int

Code returns the integer code of the coder.

func (DefaultCoder) HTTPStatus added in v1.3.1

func (coder DefaultCoder) HTTPStatus() int

HTTPStatus returns the associated HTTP status code, if any. Otherwise, returns 200.

func (DefaultCoder) Reference added in v1.3.1

func (coder DefaultCoder) Reference() string

Reference returns the reference document.

func (DefaultCoder) String added in v1.3.1

func (coder DefaultCoder) String() string

String implements stringer. String returns the external error message, if any.

type Frame

type Frame uintptr

Frame represents a program counter inside a stack frame. For historical reasons if Frame is interpreted as a uintptr its value represents the program counter + 1.

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   function name and path of source file relative to the compile time
      GOPATH separated by \n\t (<funcname>\n\t<path>)
%+v   equivalent to %+s:%d

func (Frame) MarshalText

func (f Frame) MarshalText() ([]byte, error)

MarshalText formats a stacktrace Frame as a text string. The output is the same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.

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 formats the stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the stack
%v	lists the source file and line number for each Frame in the stack

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

%+v   Prints filename, function, and line number for each Frame in the stack.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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