errcode

package
v1.12.3 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2025 License: MIT Imports: 10 Imported by: 0

README

errcode

Error codes usually include system-level error codes and business-level error codes, consisting of a total of 6 decimal digits, e.g. 200101

Error code structure:

First digit Middle three digits Last two digits
1 is http system-level error
2 is http business-level error
3 is grpc system-level error
4 is grpc system-level error
Table or module number, range 1~1000 Custom number, range 1~100

Error code ranges:

Service Type System-level Error Code Range Business-level Error Code Range
http 100000 ~ 200000 200000 ~ 300000
grpc 300000 ~ 400000 400000 ~ 500000

Example of use

Example of http error code usage

Web services created based on SQL, use the following error code:

    import "github.com/go-dev-frame/sponge/pkg/gin/response"

    // return error
    response.Error(c, ecode.InvalidParams)
    // rewrite error messages
    response.Error(c, ecode.InvalidParams.RewriteMsg("custom error message"))

    // convert error code to standard http status code
    response.Out(c, ecode.InvalidParams)
    // convert error code to standard http status code, and rewrite error messages
    response.Out(c, ecode.InvalidParams.RewriteMsg("custom error message"))

Web services created based on Protobuf, use the following error code:

    // return error
    return nil, ecode.InvalidParams.Err()
    // rewrite error messages
    return nil, ecode.InvalidParams.Err("custom error message")

    // convert error code to standard http status code
    return nil, ecode.InvalidParams.ErrToHTTP()
    // convert error code to standard http status code, and rewrite error messages
    return nil, ecode.InvalidParams.ErrToHTTP("custom error message")

Example of grpc error code usage

    // return error
    return nil, ecode.StatusInvalidParams.Err()
    // rewrite error messages
    return nil, ecode.StatusInvalidParams.Err("custom error message")

    // convert error code to standard grpc status code
    return nil, ecode.StatusInvalidParams.ToRPCErr()
    // convert error code to standard grpc status code, and rewrite error messages
    return nil, ecode.StatusInvalidParams.ToRPCErr("custom error message")

    // convert error code to standard http status code
    return nil, ecode.StatusInvalidParams.ErrToHTTP()
    // convert error code to standard http status code, and rewrite error messages
    return nil, ecode.StatusInvalidParams.ErrToHTTP("custom error message")

Documentation

Overview

Package errcode is used for http and grpc error codes, include system-level error codes and business-level error codes

Index

Constants

View Source
const ToHTTPCodeLabel = "[standard http code]"

ToHTTPCodeLabel need to convert to standard http code label

Variables

View Source
var (
	Success             = NewError(0, "ok")
	InvalidParams       = NewError(100001, "Invalid Parameter")
	Unauthorized        = NewError(100002, "Unauthorized")
	InternalServerError = NewError(100003, "Internal Server Error")
	NotFound            = NewError(100004, "Not Found")
	Timeout             = NewError(100006, "Request Timeout")
	TooManyRequests     = NewError(100007, "Too Many Requests")
	Forbidden           = NewError(100008, "Forbidden")
	LimitExceed         = NewError(100009, "Limit Exceed")
	DeadlineExceeded    = NewError(100010, "Deadline Exceeded")
	AccessDenied        = NewError(100011, "Access Denied")
	MethodNotAllowed    = NewError(100012, "Method Not Allowed")
	ServiceUnavailable  = NewError(100013, "Service Unavailable")

	Canceled           = NewError(100014, "Canceled")
	Unknown            = NewError(100015, "Unknown")
	PermissionDenied   = NewError(100016, "Permission Denied")
	ResourceExhausted  = NewError(100017, "Resource Exhausted")
	FailedPrecondition = NewError(100018, "Failed Precondition")
	Aborted            = NewError(100019, "Aborted")
	OutOfRange         = NewError(100020, "Out Of Range")
	Unimplemented      = NewError(100021, "Unimplemented")
	DataLoss           = NewError(100022, "Data Loss")

	StatusBadGateway = NewError(100023, "Bad Gateway")

	// Deprecated: use Conflict instead
	AlreadyExists = NewError(100005, "Already Exists")
	Conflict      = NewError(100409, "Conflict")
	TooEarly      = NewError(100425, "Too Early")
)

http system level error code, error code range 10000~20000

View Source
var (
	StatusSuccess = NewRPCStatus(0, "ok")

	StatusCanceled            = NewRPCStatus(300001, "Canceled")
	StatusUnknown             = NewRPCStatus(300002, "Unknown")
	StatusInvalidParams       = NewRPCStatus(300003, "Invalid Parameter")
	StatusDeadlineExceeded    = NewRPCStatus(300004, "Deadline Exceeded")
	StatusNotFound            = NewRPCStatus(300005, "Not Found")
	StatusAlreadyExists       = NewRPCStatus(300006, "Already Exists")
	StatusPermissionDenied    = NewRPCStatus(300007, "Permission Denied")
	StatusResourceExhausted   = NewRPCStatus(300008, "Resource Exhausted")
	StatusFailedPrecondition  = NewRPCStatus(300009, "Failed Precondition")
	StatusAborted             = NewRPCStatus(300010, "Aborted")
	StatusOutOfRange          = NewRPCStatus(300011, "Out Of Range")
	StatusUnimplemented       = NewRPCStatus(300012, "Unimplemented")
	StatusInternalServerError = NewRPCStatus(300013, "Internal Server Error")
	StatusServiceUnavailable  = NewRPCStatus(300014, "Service Unavailable")
	StatusDataLoss            = NewRPCStatus(300015, "Data Loss")
	StatusUnauthorized        = NewRPCStatus(300016, "Unauthorized")

	StatusTimeout          = NewRPCStatus(300017, "Request Timeout")
	StatusTooManyRequests  = NewRPCStatus(300018, "Too Many Requests")
	StatusForbidden        = NewRPCStatus(300019, "Forbidden")
	StatusLimitExceed      = NewRPCStatus(300020, "Limit Exceed")
	StatusMethodNotAllowed = NewRPCStatus(300021, "Method Not Allowed")
	StatusAccessDenied     = NewRPCStatus(300022, "Access Denied")
	StatusConflict         = NewRPCStatus(300023, "Conflict")
)

rpc system level error code with status prefix, error code range 30000~40000

View Source
var SkipResponse = errors.New("skip response") //nolint

SkipResponse skip response

Functions

func GetErrorCode

func GetErrorCode(err error) int

GetErrorCode get Error code from error returned by http invoke

func GetStatusCode

func GetStatusCode(err error) codes.Code

GetStatusCode get status code from error returned by RPC invoke

func HCode

func HCode(num int) int

HCode Generate an error code between 200000 and 300000 according to the number

http service level error code, Err prefix, example.

var ( ErrUserCreate = NewError(HCode(1)+1, "failed to create user") // 200101 ErrUserDelete = NewError(HCode(1)+2, "failed to delete user") // 200102 ErrUserUpdate = NewError(HCode(1)+3, "failed to update user") // 200103 ErrUserGet = NewError(HCode(1)+4, "failed to get user details") // 200104 )

func ListGRPCErrCodes

func ListGRPCErrCodes(w http.ResponseWriter, _ *http.Request)

ListGRPCErrCodes list grpc error codes, http handle func

func RCode

func RCode(num int) codes.Code

RCode Generate an error code between 400000 and 500000 according to the number

rpc service level error code, status prefix, example.

var (
	StatusUserCreate = NewRPCStatus(RCode(1)+1, "failed to create user")		// 400101
	StatusUserDelete = NewRPCStatus(RCode(1)+2, "failed to delete user")		// 400102
	StatusUserUpdate = NewRPCStatus(RCode(1)+3, "failed to update user")		// 400103
	StatusUserGet    = NewRPCStatus(RCode(1)+4, "failed to get user details")	// 400104
)

func ShowConfig

func ShowConfig(jsonData []byte) func(w http.ResponseWriter, r *http.Request)

ShowConfig show config info @Summary show config info @Description show config info @Tags system @Accept json @Produce json @Router /config [get]

Types

type Detail

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

Detail error details

func Any

func Any(key string, val interface{}) Detail

Any type key value

func (*Detail) String

func (d *Detail) String() string

String detail key-value

type ErrInfo

type ErrInfo struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

ErrInfo error info

func ListHTTPErrCodes

func ListHTTPErrCodes() []ErrInfo

ListHTTPErrCodes list http error codes

type Error

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

Error error

func NewError

func NewError(code int, msg string, details ...string) *Error

NewError create a new error message

func ParseError

func ParseError(err error) *Error

ParseError parsing out error codes from error messages

func ToHTTPErr

func ToHTTPErr(st *status.Status) *Error

ToHTTPErr converted to http error

func (*Error) Code

func (e *Error) Code() int

Code get error code

func (*Error) Details

func (e *Error) Details() []string

Details get error code details

func (*Error) Err

func (e *Error) Err(msg ...string) error

Err convert to standard error, if there is a parameter 'msg', it will replace the original message.

func (*Error) ErrToHTTP

func (e *Error) ErrToHTTP(msg ...string) error

ErrToHTTP convert to standard error add ToHTTPCodeLabel to error message, use it if you need to convert to standard HTTP status code, if there is a parameter 'msg', it will replace the original message. Tips: you can call the GetErrorCode function to get the standard HTTP status code.

func (*Error) Msg

func (e *Error) Msg() string

Msg get error code message

func (*Error) NeedHTTPCode

func (e *Error) NeedHTTPCode() bool

NeedHTTPCode need to convert to standard http code

func (*Error) RewriteMsg

func (e *Error) RewriteMsg(msg string) *Error

RewriteMsg rewrite error message

func (*Error) ToHTTPCode

func (e *Error) ToHTTPCode() int

ToHTTPCode convert to http error code

func (*Error) WithDetails

func (e *Error) WithDetails(details ...string) *Error

WithDetails add error details

func (*Error) WithOutMsg

func (e *Error) WithOutMsg(msg string) *Error

WithOutMsg out error message Deprecated: use RewriteMsg instead

func (*Error) WithOutMsgI18n

func (e *Error) WithOutMsgI18n(langMsg map[int]map[string]string, lang string) *Error

WithOutMsgI18n out error message i18n langMsg example:

map[int]map[string]string{
		20010: {
			"en-US": "login failed",
			"zh-CN": "登录失败",
		},
	}

lang BCP 47 code https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oe376/6c085406-a698-4e12-9d4d-c3b0ee3dbc4a

type RPCStatus

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

RPCStatus rpc status

func NewRPCStatus

func NewRPCStatus(code codes.Code, msg string) *RPCStatus

NewRPCStatus create a new rpc status

func (*RPCStatus) Code

func (s *RPCStatus) Code() codes.Code

Code get code

func (*RPCStatus) Err

func (s *RPCStatus) Err(desc ...string) error

Err return error if there is a parameter 'desc', it will replace the original message

func (*RPCStatus) ErrToHTTP

func (s *RPCStatus) ErrToHTTP(desc ...string) error

ErrToHTTP convert to standard error add ToHTTPCodeLabel to error message, usually used when HTTP calls the GRPC API, if there is a parameter 'desc', it will replace the original message.

func (*RPCStatus) Msg

func (s *RPCStatus) Msg() string

Msg get message

func (*RPCStatus) ToRPCCode

func (s *RPCStatus) ToRPCCode() codes.Code

ToRPCCode converted to standard RPC error code

func (*RPCStatus) ToRPCErr

func (s *RPCStatus) ToRPCErr(desc ...string) error

ToRPCErr converted to standard RPC error, use it if you need to convert to standard RPC errors, if there is a parameter 'desc', it will replace the original message.

type Responser

type Responser interface {
	Success(ctx *gin.Context, data interface{})
	ParamError(ctx *gin.Context, err error)
	Error(ctx *gin.Context, err error) bool
}

Responser response interface

func NewResponser

func NewResponser(isFromRPC bool, httpErrors []*Error, rpcStatus []*RPCStatus) Responser

NewResponser creates a new responser, if isFromRPC=true, it means return from rpc, otherwise default return from http

Jump to

Keyboard shortcuts

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