errcode

package module
v0.0.0-...-5b49010 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2022 License: Apache-2.0 Imports: 19 Imported by: 0

README

errcode

Go return enhanced status

Documentation

Overview

Package errcode A simple test helper see: https://github.com/google/googletest/blob/master/googletest/docs/primer.md

Index

Constants

This section is empty.

Variables

View Source
var (
	OK               = addCode(code.Code_OK, http.StatusOK, "")                                // #0
	Cancelled        = addCode(code.Code_CANCELLED, 499, "已取消")                                // #1
	Unknown          = addCode(code.Code_UNKNOWN, http.StatusInternalServerError, "未知错误")      // #2
	InvalidArgument  = addCode(code.Code_INVALID_ARGUMENT, http.StatusBadRequest, "非法输入")      // #3
	DeadlineExceeded = addCode(code.Code_DEADLINE_EXCEEDED, http.StatusGatewayTimeout, "超时错误") // #4
	// Some requested entity (e.g., file or directory) was not found.
	//
	// Note to server developers: if a request is denied for an entire class
	// of users, such as gradual feature rollout or undocumented whitelist,
	// `NOT_FOUND` may be used. If a request is denied for some users within
	// a class of users, such as user-based access control, `PERMISSION_DENIED`
	// must be used.
	//
	// HTTP Mapping: 404 Not Found
	NotFound = addCode(code.Code_NOT_FOUND, http.StatusNotFound, "没找到对象") // #5
	// The entity that a client attempted to create (e.g., file or directory)
	// already exists.
	//
	// HTTP Mapping: 409 Conflict
	AlreadyExists = addCode(code.Code_ALREADY_EXISTS, http.StatusConflict, "已经存在") // #6
	// The caller does not have permission to execute the specified
	// operation. `PERMISSION_DENIED` must not be used for rejections
	// caused by exhausting some resource (use `RESOURCE_EXHAUSTED`
	// instead for those errors). `PERMISSION_DENIED` must not be
	// used if the caller can not be identified (use `UNAUTHENTICATED`
	// instead for those errors). This error code does not imply the
	// request is valid or the requested entity exists or satisfies
	// other pre-conditions.
	//
	// HTTP Mapping: 403 Forbidden
	PermissionDenied = addCode(code.Code_PERMISSION_DENIED, http.StatusForbidden, "权限错误") // #7
	// The request does not have valid authentication credentials for the
	// operation.
	//
	// HTTP Mapping: 401 Unauthorized
	Unauthenticated = addCode(code.Code_UNAUTHENTICATED, http.StatusUnauthorized, "未通过身份验证") // #16
	// Some resource has been exhausted, perhaps a per-user quota, or
	// perhaps the entire file system is out of space.
	//
	// HTTP Mapping: 429 Too Many Requests
	ResourceExhausted = addCode(code.Code_RESOURCE_EXHAUSTED, http.StatusTooManyRequests, "资源耗尽") // #8

	FailedPrecondition = addCode(code.Code_FAILED_PRECONDITION, http.StatusBadRequest, "非预期状态") // #9
	// The operation was aborted, typically due to a concurrency issue such as
	// a sequencer check failure or transaction abort.
	//
	// See the guidelines above for deciding between `FAILED_PRECONDITION`,
	// `ABORTED`, and `UNAVAILABLE`.
	//
	// HTTP Mapping: 409 Conflict
	Aborted = addCode(code.Code_ABORTED, http.StatusConflict, "访问拒绝") // #10
	// The 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.
	//
	// HTTP Mapping: 400 Bad Request
	OutOfRange = addCode(code.Code_OUT_OF_RANGE, http.StatusBadRequest, "超出范围") // #11
	// The operation is not implemented or is not supported/enabled in this
	// service.
	//
	// HTTP Mapping: 501 Not Implemented
	Unimplemented = addCode(code.Code_UNIMPLEMENTED, http.StatusNotImplemented, "没有实现") // #12
	// Internal errors.  This means that some invariants expected by the
	// underlying system have been broken.  This error code is reserved
	// for serious errors.
	//
	// HTTP Mapping: 500 Internal Server Error
	Internal = addCode(code.Code_INTERNAL, http.StatusInternalServerError, "内部错误") // #13
	// The service is currently unavailable.  This is most likely a
	// transient condition, which can be corrected by retrying with
	// a backoff.
	//
	// See the guidelines above for deciding between `FAILED_PRECONDITION`,
	// `ABORTED`, and `UNAVAILABLE`.
	//
	// HTTP Mapping: 503 Service Unavailable
	Unavailable = addCode(code.Code_UNAVAILABLE, http.StatusServiceUnavailable, "不可用") // #14
	// Unrecoverable data loss or corruption.
	//
	// HTTP Mapping: 500 Internal Server Error
	DataLoss = addCode(code.Code_DATA_LOSS, http.StatusInternalServerError, "数据丢失") // #15

)

All common errcode

View Source
var File_proto_rpc_status_proto protoreflect.FileDescriptor

Functions

func CheckError

func CheckError(c Codes) bool

CheckError Check whether to be Error

func CheckIsNil

func CheckIsNil(i interface{}) bool

func CheckIsNotNil

func CheckIsNotNil(i interface{}) bool

func CheckOk

func CheckOk(c Codes) bool

CheckOk Check whether to be OK

func Context

func Context(e Codes) context.Context

Context get current context or a new context

func Equal

func Equal(a, b Codes) bool

Equal equal a and b by code int.

func EqualError

func EqualError(code Codes, err error) bool

EqualError equal error

func ExpectEQ

func ExpectEQ(t *testing.T, expected, actual interface{}, msg ...string)

期望两者相同

func ExpectErr

func ExpectErr(t *testing.T, err error, msg ...string)

期望出现 error

func ExpectFalse

func ExpectFalse(t *testing.T, condition bool, msg ...string)

func ExpectGE

func ExpectGE(t *testing.T, val1, val2 interface{}, msg ...string)

Less Than

func ExpectGT

func ExpectGT(t *testing.T, val1, val2 interface{}, msg ...string)

Less Than

func ExpectLE

func ExpectLE(t *testing.T, val1, val2 interface{}, msg ...string)

func ExpectLT

func ExpectLT(t *testing.T, val1, val2 interface{}, msg ...string)

Less Than

func ExpectLen

func ExpectLen(t *testing.T, length int, actual interface{}, msg ...string)

期望长度 TODO(yu): test cases

func ExpectNE

func ExpectNE(t *testing.T, expected, actual interface{}, msg ...string)

func ExpectNil

func ExpectNil(t *testing.T, actual interface{}, msg ...string)

func ExpectNoErr

func ExpectNoErr(t *testing.T, err error, msg ...string)

func ExpectNotNil

func ExpectNotNil(t *testing.T, actual interface{}, msg ...string)

func ExpectTrue

func ExpectTrue(t *testing.T, condition bool, msg ...string)

func IsError

func IsError(c Codes) bool

IsError is an alias of CheckError

func IsOk

func IsOk(c Codes) bool

IsOk is an alias of CheckOk

func RegisterHttpCode

func RegisterHttpCode(code int, httpCode int)

func RegisterMessage

func RegisterMessage(code int, message string)

func RegisterMessages

func RegisterMessages(cm map[int]string)

func TestFunc

func TestFunc(f func()) (ret string)

Note: Don't Use the test out of assert

func TestWrap

func TestWrap(skip int, concl string, cmp func() bool, msg ...string) string

Types

type Code

type Code int

A Code is an int error code spec.

func Int

func Int(i int) Code

Int parse code int to error.

func New

func New(e int) Code

New a errcode.Codes by int value. NOTE: errcode must unique in global, the New will check repeat and then panic.

func RegisterCode

func RegisterCode(c code.Code, httpCode int, message string) Code

func String

func String(e string) Code

String parse code string to error.

func (Code) Code

func (e Code) Code() int

Code return error code

func (Code) Context

func (e Code) Context() context.Context

func (Code) Details

func (e Code) Details() []interface{}

Details return details.

func (Code) Error

func (e Code) Error() string

func (Code) HttpCode

func (e Code) HttpCode() int

func (Code) Message

func (e Code) Message() string

Message return error message

func (Code) StackEntries

func (e Code) StackEntries() (details []*errdetails.DebugInfo)

func (Code) WithCancel

func (e Code) WithCancel() (codes Codes, cancel context.CancelFunc)

func (Code) WithContext

func (e Code) WithContext(ctx context.Context) Codes

func (Code) WithDeadline

func (e Code) WithDeadline(d time.Time) (Codes, context.CancelFunc)

func (Code) WithTimeout

func (e Code) WithTimeout(timeout time.Duration) (Codes, context.CancelFunc)

func (Code) WithValue

func (e Code) WithValue(key, val interface{}) Codes

type Codes

type Codes interface {
	// Error sometimes Error return Code in string form
	// NOTE: don't use Error in monitor report even it also work for now
	Error() string
	// Code get error code.
	Code() int
	// Message get code message.
	Message() string
	// Details get error detail,it may be nil.
	Details() []interface{}

	HttpCode() int

	// StackEntries return nil if it is a code
	StackEntries() (details []*errdetails.DebugInfo)

	Context() context.Context

	WithContext(ctx context.Context) Codes
	WithCancel() (codes Codes, cancel context.CancelFunc)
	WithDeadline(d time.Time) (Codes, context.CancelFunc)
	WithTimeout(timeout time.Duration) (Codes, context.CancelFunc)
	WithValue(key, val interface{}) Codes
}

Codes errcode error interface which has a code & message.

func Cause

func Cause(e error) Codes

Cause cause from error to ecode.

func FromError

func FromError(e error, code2 Code) Codes

FromError create status from error Pay attention to the difference with Cause()

func FromProto

func FromProto(pbMsg proto.Message) Codes

FromProto new status from grpc detail

func WithCancel

func WithCancel(e Codes) (codes Codes, cancel context.CancelFunc)

func WithContext

func WithContext(e Codes, ctx context.Context) Codes

WithContext create a new context

func WithDeadline

func WithDeadline(e Codes, d time.Time) (Codes, context.CancelFunc)

func WithTimeout

func WithTimeout(e Codes, timeout time.Duration) (Codes, context.CancelFunc)

func WithValue

func WithValue(e Codes, key, val interface{}) Codes

type CompareType

type CompareType int

type PBStatus

type PBStatus struct {

	// The status code, which should be an enum value of
	// [google.rpc.Code][google.rpc.Code].
	Code code.Code `protobuf:"varint,1,opt,name=code,proto3,enum=rcrai.rpc.Code" json:"code,omitempty"`
	// A developer-facing error message, which should be in English. Any
	// user-facing error message should be localized and sent in the
	// [google.rpc.Status.details][google.rpc.Status.details] field, or localized
	// by the client.
	Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
	// A list of messages that carry the error details.  There is a common set of
	// message types for APIs to use.
	Details []*anypb.Any `protobuf:"bytes,3,rep,name=details,proto3" json:"details,omitempty"`
	// contains filtered or unexported fields
}

The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be:

- Simple to use and understand for most users - Flexible enough to meet unexpected needs

Overview

The `Status` message contains three pieces of data: error code, error message, and error details. The error code should be an enum value of [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, put the localized message in the error details or localize it in the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package `google.rpc` that can be used for common error conditions.

Language mapping

The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire format. When the `Status` message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C.

Other uses

The error model and the `Status` message can be used in a variety of environments, either with or without APIs, to provide a consistent developer experience across different environments.

Example uses of this error model include:

  • Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the normal response to indicate the partial errors.
  • Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error reporting.
  • Batch operations. If a client uses batch request and batch response, the `Status` message should be used directly inside batch response, one for each error sub-response.
  • Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the `Status` message.
  • Logging. If some API errors are stored in logs, the message `Status` could be used directly after any stripping needed for security/privacy reasons.

func (*PBStatus) GetCode

func (x *PBStatus) GetCode() code.Code

func (*PBStatus) GetDetails

func (x *PBStatus) GetDetails() []*anypb.Any

func (*PBStatus) GetMessage

func (x *PBStatus) GetMessage() string

func (*PBStatus) ProtoMessage

func (*PBStatus) ProtoMessage()

func (*PBStatus) ProtoReflect

func (x *PBStatus) ProtoReflect() protoreflect.Message

func (*PBStatus) Reset

func (x *PBStatus) Reset()

func (*PBStatus) String

func (x *PBStatus) String() string

type Status

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

Status statusError is an alias of a status proto implement Codes

func Error

func Error(code Code, message string) *Status

Error new status with code and message

func Errorf

func Errorf(code Code, format string, args ...interface{}) *Status

Errorf new status with code and message

func FromCode

func FromCode(code2 Code) *Status

FromCode create status from ecode

func WrapCodes

func WrapCodes(codes Codes) *Status

WrapCodes create status from Codes 这个是为了对之前的代码做一些 workaround。在之前代码我们使用 *Status 作为

func (*Status) Code

func (s *Status) Code() int

Code return error code

func (*Status) Context

func (s *Status) Context() context.Context

func (*Status) Descriptor deprecated

func (*Status) Descriptor() ([]byte, []int)

Deprecated: Use Status.ProtoReflect.Descriptor instead.

func (*Status) Details

func (s *Status) Details() []interface{}

Details return error details

func (*Status) Equal

func (s *Status) Equal(err error) bool

Equal for compatible.

func (*Status) Error

func (s *Status) Error() string

Error implement error

func (*Status) HttpCode

func (s *Status) HttpCode() int

func (*Status) MergeStackEntries

func (s *Status) MergeStackEntries(rhs Codes) *Status

func (*Status) Message

func (s *Status) Message() string

Message return error message for developer

func (*Status) Proto

func (s *Status) Proto() *PBStatus

Proto return origin protobuf message

func (*Status) StackEntries

func (s *Status) StackEntries() (details []*errdetails.DebugInfo)

func (*Status) WithCancel

func (s *Status) WithCancel() (codes Codes, cancel context.CancelFunc)

func (*Status) WithContext

func (s *Status) WithContext(ctx context.Context) Codes

func (*Status) WithDeadline

func (s *Status) WithDeadline(d time.Time) (Codes, context.CancelFunc)

func (*Status) WithDetails

func (s *Status) WithDetails(pbs ...proto.Message) (*Status, error)

WithDetails WithDetails

func (*Status) WithStackEntries

func (s *Status) WithStackEntries(msg string) *Status

func (*Status) WithTimeout

func (s *Status) WithTimeout(timeout time.Duration) (Codes, context.CancelFunc)

func (*Status) WithValue

func (s *Status) WithValue(key, val interface{}) Codes

Jump to

Keyboard shortcuts

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