metacode

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2023 License: MPL-2.0 Imports: 8 Imported by: 4

README

项目简介

metadata 用于储存各种元信息

code错误码一般被用来进行异常传递,且需要具有携带message文案信息的能力。

在这里,错误码被设计成Codes接口,声明如下:

// 错误代码接口,其中包含代码和消息.
type Codes interface {
    // 有时错误返回字符串形式的代码
    // 注意:请勿在监控器报告中使用“error”,即使它现在也可以使用
    Error() string
    // 获取错误代码.
    Code() int
    // 获取错误信息.
    Message() string
    // 获取错误详细信息,可能为nil.
    Details() []interface{}
}

// Code是int型错误代码规范.
type Code int

可以看到该接口一共有四个方法,且type Code int结构体实现了该接口。

注册message

一个Code错误码可以对应一个message,默认实现会从全局变量_messages中获取,业务可以将自定义Code对应的message通过调用Register方法的方式传递进去,如:

cms := map[int]string{
    0: "很好很强大!",
    -304: "啥都没变啊~",
    -404: "啥都没有啊~",
}
metacode.Register(cms)

fmt.Println(metacode.OK.Message()) // 输出:很好很强大!

注意:map[int]string类型并不是绝对,比如有业务要支持多语言的场景就可以扩展为类似map[int]LangStruct的结构,因为全局变量_messagesatomic.Value类型,只需要修改对应的Message方法实现即可。

Details

Details接口为gRrc预留,gRrc传递异常会将服务端的错误码pb序列化之后赋值给Details,客户端拿到之后反序列化得到,具体可阅读status的实现:

  1. code包内的Status结构体实现了Codes接口
  2. grpc/status包内包装了metacode.Statusgrpc.Status进行互相转换的方法
  3. grpcclientserver则使用转换方法将gRrc底层返回的error最终转换为metacode.Status

转换为code

错误码转换有以下两种情况:

  1. 因为框架传递错误是靠code错误码,比如mvc框架返回的code字段默认就是数字,那么客户端接收到如{"code":-404}的话,可以使用mc := metacode.Int(-404)mc := metacode.String("-404")来进行转换。
  2. 在项目中dao层返回一个错误码,往往返回参数类型建议为error而不是metacode.Codes,因为error更通用,那么上层service就可以使用mc := metacode.Cause(err)进行转换。

判断

错误码判断是否相等:

  1. codecode判断使用:metacode.Equal(mc1, mc2)
  2. codeerror判断使用:metacode.EqualError(mc, err)

使用工具生成

使用proto协议定义错误码,格式如下:

// user.proto
syntax = "proto3";

package code;

enum UserErrCode { 
  UserUndefined = 0; // 因protobuf协议限制必须存在!!!无意义的0,工具生成代码时会忽略该参数
  UserNotLogin = 123; // 正式错误码
}

需要注意以下几点:

  1. 必须是enum类型,且名字规范必须以"ErrCode"结尾,如:UserErrCode
  2. 因为protobuf协议限制,第一个enum值必须为无意义的0

使用feo tool protoc --code user.proto进行生成

Documentation

Index

Constants

View Source
const (

	// Network
	RemoteIP   = "remote_ip"
	RemotePort = "remote_port"
	ServerAddr = "server_addr"
	ClientAddr = "client_addr"

	// Trace
	Trace  = "trace"
	Caller = "caller"

	// Timeout
	Timeout = "timeout"

	// Dispatch
	Errors   = "errors"
	Requests = "requests"

	// Mirror
	Mirror = "mirror"

	// Mid 外网账户用户id
	Mid = "mid" // NOTE: !!!业务可重新修改key名!!!

	// Device 客户端信息
	Device = "device"

	// Criticality 重要性
	Criticality = "criticality"
)

metacode common key

Variables

View Source
var (
	OK      = add(0) // 正确
	Success = add(1) // 成功

	NotModified        = add(-304) // 木有改动
	TemporaryRedirect  = add(-307) // 撞车跳转
	RequestErr         = add(-400) // 请求错误
	Unauthorized       = add(-401) // 未认证
	AccessDenied       = add(-403) // 访问权限不足
	NothingFound       = add(-404) // 啥都木有
	MethodNotAllowed   = add(-405) // 不支持该方法
	Conflict           = add(-409) // 冲突
	Canceled           = add(-498) // 客户端取消请求
	ServerErr          = add(-500) // 服务器错误
	ServiceUnavailable = add(-503) // 过载保护,服务暂不可用
	Deadline           = add(-504) // 服务调用超时
	LimitExceed        = add(-509) // 超出限制
	ValidateErr        = add(-512) // 服务器请求参数校验出错
)

All common code

Functions

func Bool

func Bool(ctx context.Context, key string) bool

Bool get boolean from metadata in context use strconv.Parse.

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 Int64

func Int64(ctx context.Context, key string) int64

Int64 get int64 value from metadata in context

func IsIncomingKey

func IsIncomingKey(key string) (ok bool)

IsIncomingKey represent this key should extract from rpc metadata.

func IsOutgoingKey

func IsOutgoingKey(key string) bool

IsOutgoingKey represent this key should propagate by rpc.

func NewContext

func NewContext(ctx context.Context, md Metadata) context.Context

NewContext creates a new context with md attached.

func Range

func Range(ctx context.Context, rangeFunc func(key string, value interface{}), filterFunc ...func(key string) bool)

Range range value from metadata in context filtered by filterFunc.

func Register

func Register(l string, cm map[int]string)

Register register code message map.

func ToString

func ToString(ctx context.Context, key string) string

String get string value from metacode in context

func Value

func Value(ctx context.Context, key string) interface{}

Value get value from metadata in context return nil if not found

func WithContext

func WithContext(c context.Context) context.Context

WithContext return no deadline context and retain metadata.

Types

type Code

type Code int

Code是int型错误代码规范.

func IntCode

func IntCode(i int) Code

Int parse code int to error.

func NewCode

func NewCode(c int) Code

NewCode 新建一个新的元数据。 注意:代码必须在全局范围内唯一,新代码将检查重复,然后出现恐慌。

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

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

Details return details.

func (Code) Error

func (e Code) Error() string

func (Code) Message

func (e Code) Message(l string) string

Message return error message

type Codes

type Codes interface {
	// Error 有时错误返回字符串形式的代码
	// 注意:请勿在监控器报告中使用“error”,即使它现在也可以使用
	Error() string
	// Code 获取错误代码.
	Code() int
	// Message 获取错误信息.
	// param l string 语言
	Message(l string) string
	// Details 获取错误详细信息,可能为nil.
	Details() []interface{}
}

错误代码接口,其中包含代码和消息.

func Cause

func Cause(e error) Codes

Cause cause from error to code.

func FromProto

func FromProto(pbMsg proto.Message) Codes

FromProto new status from gRpc detail

type Metadata

type Metadata map[string]interface{}

Metadata is a mapping from metadata keys to values.

func FromContext

func FromContext(ctx context.Context) (md Metadata, ok bool)

FromContext returns the incoming metacode in ctx if it exists. The returned Metadata should not be modified. Writing to it may cause races. Modification should be made to copies of the returned Metadata.

func Join

func Join(mds ...Metadata) Metadata

Join joins any number of mds into a single Metadata. The order of values for each key is determined by the order in which the mds containing those values are presented to Join.

func NewMetadata

func NewMetadata(m map[string]interface{}) Metadata

New creates an Metadata from a given key-value map.

func Pairs

func Pairs(kv ...interface{}) Metadata

Pairs returns an Metadata formed by the mapping of key, value ... Pairs panics if len(kv) is odd.

func (Metadata) Copy

func (md Metadata) Copy() Metadata

Copy returns a copy of md.

func (Metadata) Len

func (md Metadata) Len() int

Len returns the number of items in md.

type Status

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

Status statusError is an alias of a status proto implement metacode.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(code Code) *Status

FromCode create status from code

func (*Status) Code

func (s *Status) Code() int

Code return error code

func (*Status) Details

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

Details return error details

func (*Status) Error

func (s *Status) Error() string

Error implement error

func (*Status) Message

func (s *Status) Message(_ string) string

Message return error message for developer

func (*Status) Proto

func (s *Status) Proto() *types.Status

Proto return origin protobuf message

func (*Status) WithDetails

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

WithDetails WithDetails

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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