Categorygithub.com/go-leo/errors
modulepackage
1.2.2
Repository: https://github.com/go-leo/errors.git
Documentation: pkg.go.dev

# README

errors

简单易用、可携带业务错误码的错误处理包. 基于 pkg/errors 加入了更丰富的功能,更适用在微服务体系下.

quick start

  1. cd ./example
  2. go run ./cmd
  3. 如下请求查看返回值和日志信息
    // 参数错误
    curl --location --request GET 'http://127.0.0.1:8080/user?uid=a'
    
    // 业务错误
    curl --location --request GET 'http://127.0.0.1:8080/user?uid=1'
    curl --location --request GET 'http://127.0.0.1:8080/user?uid=99'
    
    // 内部错误
    curl --location --request GET 'http://127.0.0.1:8080/user?uid=10000'
    

errors generate

  1. 安装 go install github.com/go-leo/errors/codegen
  2. 定义错误码文件
     package code
     //go:generate codegen -type=int
    
     // base: base errors.
     const (
         // ErrUnknown - 500: Internal server error.
         ErrUnknown int = iota + 100001
    
         // ErrBind - 400: Error occurred while binding the request body to the struct.
         ErrBind
    
         // ErrValidation - 400: Validation failed.
         ErrValidation
     )
    
  3. 实现错误注册方法
     package code
    
     import (
         "net/http"
    
         "github.com/go-leo/errors"
         "golang.org/x/exp/slices"
     )
    
     // ErrCode implements `panda/pkg/errors`.Coder interface.
     type ErrCode struct {
         // C refers to the code of the ErrCode.
         C int `json:"code,omitempty"`
    
         // HTTP status that should be used for the associated error code.
         HTTP int `json:"http,omitempty"`
    
         // External (user) facing error text.
         Ext string `json:"msg,omitempty"`
    
         // Ref specify the reference document.
         Ref string `json:"ref,omitempty"`
     }
    
     var _ errors.Coder = &ErrCode{}
    
     // Code returns the integer code of ErrCode.
     func (coder ErrCode) Code() int {
         return coder.C
     }
    
     // String implements stringer. String returns the external error message,
     // if any.
     func (coder ErrCode) String() string {
         return coder.Ext
     }
    
     // Reference returns the reference document.
     func (coder ErrCode) Reference() string {
         return coder.Ref
     }
    
     // HTTPStatus returns the associated HTTP status code, if any. Otherwise,
     // returns 200.
     func (coder ErrCode) HTTPStatus() int {
         if coder.HTTP == 0 {
             return http.StatusInternalServerError
         }
    
         return coder.HTTP
     }
    
     //nolint: unparam // .
     func register(code int, httpStatus int, message string, refs ...string) {
         found := slices.Contains([]int{200, 400, 401, 403, 404, 500}, httpStatus)
         if !found {
             panic("http code not in `200, 400, 401, 403, 404, 500`")
         }
    
         var reference string
         if len(refs) > 0 {
             reference = refs[0]
         }
    
         coder := &ErrCode{
             C:    code,
             HTTP: httpStatus,
             Ext:  message,
             Ref:  reference,
         }
    
         errors.MustRegister(coder)
     }
    
  4. 生成错误码文件
    go generate ./...
    

use error

使用生成好的错误方法

  1. 已知错误,携带业务错误码

    对于已知的异常情况可以通过业务错误码告知客户端发生的错误和原因,一般为参数错误、认证失败等; 服务端记录错误日志不包含堆栈信息;

  2. 未知错误,携带堆栈信息

    对于未知错误需要服务端排查,服务端记录错误日志包含堆栈信息; 客户端无需关心,获取到内部错误信息即可

# Packages

Package main is a tool to automate the creation of code init function.

# Functions

As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
Cause returns the underlying cause of the error, if possible.
FromGRPCCode converts a gRPC error code into the corresponding HTTP response status.
GetCoder get Coder with code not found return ErrUnknown note: can not be change.
GRPCCodeStatus convert code to grpc *status.Status.
GRPCStatus convert error to grpc *status.Status.
Is reports whether any error in err's chain matches target.
IsCode reports whether any error in err's chain contains the given error code.
MustRegister register a user define error code.
New return a std error.
NewWithCode new error has default describe.
NewWithCodeX new error with code with options.
NewWithStack return a error with stack.
ParseCoder parse any error into *WithCode.
Register register a user define error code.
set coustom maxStackDepth.
ToGRPCCode converts an HTTP error code into the corresponding gRPC response status.
Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error.
WithCode return an error annotating err with a stack trace and error code.
WithMessage annotates err with a new message.
WithMessagef annotates err with the format specifier.
WithSkipDepth set skip depth.
WithStack annotates err with a stack trace at the point WithStack was called.
WrapC return an error annotating err with a stack trace and error code.
No description provided by the author
No description provided by the author
can use this function instead WithMessage(WithStack(err), message).
can use this function instead WithMessagef(WithStack(err), format, args...).

# Constants

ClientClosed is non-standard http status code, which defined by nginx.

# Variables

global default error codes.
DefaultConverter default converter.
No description provided by the author
global default error codes.
global default error codes.

# Structs

No description provided by the author

# Interfaces

Coder defines an interface for an error code detail information.
Converter is a status converter.

# Type aliases

Frame represents a program counter inside a stack frame.
StackTrace is stack of Frames from innermost (newest) to outermost (oldest).