errors

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 7 Imported by: 0

README

errors

Go Version License Status

English | 简体中文

github.com/felix-186/errors 是一个轻量级 Go 错误处理库,基于 github.com/pkg/errors 提供统一的错误创建、包装、响应错误结构以及超时错误归一化能力,适合在 HTTP API、表单校验和通用业务错误处理中复用。

特性

  • 统一的 ResponseError 结构,包含业务错误码、HTTP 状态码、字段名和附加数据
  • 提供常用错误构造函数与包装函数,如 NewErrorNewMsgNewResponseWrapResponse
  • 兼容 errors.Iserrors.AsUnwrap
  • 内置一组可直接复用的预定义错误值
  • 支持将 context.DeadlineExceeded 和 gRPC DeadlineExceeded 统一归一化为固定错误消息

版本说明

  • 当前模块路径:github.com/felix-186/errors
  • 当前 go.mod 要求 Go 1.21.0

安装

go get github.com/felix-186/errors

快速开始

创建普通错误
package main

import (
    "fmt"

    gtsErrors "github.com/felix-186/errors"
)

func main() {
    err := gtsErrors.NewMsg(10001, "参数错误: %s", "name")
    fmt.Println(err)
}
包装为 HTTP 400 响应错误
package main

import (
    "fmt"

    gtsErrors "github.com/felix-186/errors"
)

func main() {
    err := fmt.Errorf("name is required")
    resErr := gtsErrors.Wrap400Response(err, 10001, "请求参数不合法")
    fmt.Println(resErr)
}
创建带字段信息的响应错误
err := gtsErrors.NewResponseWithField(400, "name", 10001, nil, "字段校验失败")
处理超时错误
err := gtsErrors.NewResError(context.DeadlineExceeded)

核心类型

ResponseError

ResponseError 定义于 errors.go,用于表达统一响应错误:

type ResponseError struct {
    Code       int
    Message    string
    StatusCode int
    ERR        error
    Field      string
    Data       interface{}
}

主要方法:

  • Error() string:返回当前对外可见的错误字符串
  • Cause() error:返回底层错误;若没有底层错误,会基于 Message 合成一个新的 error
  • Unwrap() error:返回 ERR,支持标准错误链

常用 API

基础错误创建
  • NewError(code int, err error) error
  • NewMsg(code int, msg string, args ...interface{}) error
  • NewErrorMsg(code int, err error, msg string, args ...interface{}) error
响应错误创建
  • NewResponse(statusCode, code int, data interface{}, msg string, args ...interface{}) error
  • NewResponseWithField(statusCode int, field string, code int, data interface{}, msg string, args ...interface{}) error
  • New400ErrResponseWithField(field string, code int, data interface{}, msg string, args ...interface{}) error
  • New400ResponseWithField(field string, code int, msg string, args ...interface{}) error
  • New400ErrResponse(code int, data interface{}, msg string, args ...interface{}) error
  • New400Response(code int, msg string, args ...interface{}) error
  • New500Error(code int, data interface{}) error
  • New500Response(msg string, args ...interface{}) error
响应错误包装
  • WrapResponse(err error, statusCode, code int, data interface{}, msg string, args ...interface{}) error
  • WrapResponseWithField(err error, statusCode int, field string, code int, data interface{}, msg string, args ...interface{}) error
  • Wrap400ResponseWithField(err error, field string, code int, data interface{}, msg string, args ...interface{}) error
  • Wrap400ErrResponse(err error, code int, data interface{}, msg string, args ...interface{}) error
  • Wrap400Response(err error, code int, msg string, args ...interface{}) error
  • Wrap400Err(err error, code int) error
  • Wrap400ErrWithField(err error, field string, code int) error
  • Wrap500Response(err error, msg string, args ...interface{}) error
解析与辅助
  • UnWrapResponse(err error) *ResponseError
  • WrapField(err error, field string) error
  • NewResError(err error) error
  • NewResErrorMsg(err error, msg string, a ...any) error

行为说明

以下内容描述的是仓库当前实现行为:

  • ResponseError.Error() 的规则:
    • ERR == nil && Message == "" 时返回 "unknown error"
    • 只有 Message 时返回 Message
    • 只有 ERR 时返回 ERR.Error()
    • Message == ERR.Error() 时不重复拼接
    • 同时存在且不相等时返回 "message: cause"
  • Cause() 在存在底层错误时返回原始 ERR;否则返回一个基于 Message 新建的错误,即使 Message 为空也会返回非空 error
  • UnWrapResponse() 仅对直接的 *ResponseError 生效,不会沿错误链继续查找
  • NewResError / NewResErrorMsg 会将 context.DeadlineExceeded 和 gRPC codes.DeadlineExceeded 统一归一化为 "执行超时"
  • 超时归一化后不会保留原始错误链或原始错误消息
  • 导出的预定义错误是共享实例;对它们调用 WrapField() 会原地修改同一个对象

预定义错误

库中内置了一组常见错误,可直接在业务代码中复用,例如:

  • ErrBadRequest
  • ErrInvalidParent
  • ErrNotAllowDeleteWithChild
  • ErrInvalidUserName
  • ErrInvalidPassword
  • ErrNoPerm
  • ErrInvalidToken
  • ErrNotFound
  • ErrInternalServer

说明:ErrNotFound 与其他大多数预定义错误不同,它带有底层错误,且当前 HTTP 状态码为 400 而不是 404

与标准 errors 的兼容

response.go 中导出了若干别名,便于统一使用:

  • New
  • Wrap
  • Wrapf
  • WithStack
  • WithMessage
  • WithMessagef
  • Is
  • As
  • Unwrap
  • Cause
  • Errorf

其中大部分来自 github.com/pkg/errorsAs 来自标准库 errors

项目结构

.
├── errors.go         # ResponseError 定义与响应错误构造函数
├── response.go       # pkg/errors 兼容别名与预定义错误
├── res_error.go      # 超时错误归一化辅助逻辑
├── response_test.go  # 行为与兼容性测试
├── go.mod            # 模块定义
├── go.sum            # 依赖锁定
├── LICENSE           # MIT License
├── README.md         # 中文说明文档
└── README_EN.md      # English documentation

测试

go test ./...
go test ./... -cover

适用场景

  • HTTP API 统一错误返回
  • 表单字段校验错误表达
  • 业务错误码封装
  • gRPC / context 超时错误归一化

License

本项目基于 MIT License 开源。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	New          = errors.New
	Wrap         = errors.Wrap
	Wrapf        = errors.Wrapf
	WithStack    = errors.WithStack
	WithMessage  = errors.WithMessage
	WithMessagef = errors.WithMessagef
	Is           = errors.Is
	Unwrap       = errors.Unwrap
	Errorf       = errors.Errorf
	Cause        = errors.Cause
	As           = gError.As
)

定义别名

View Source
var (
	ErrBadRequest              = New400Response(400, "请求发生错误")
	ErrInvalidParent           = New400Response(400, "无效的父级节点")
	ErrNotAllowDeleteWithChild = New400Response(400, "含有子级,不能删除")
	ErrNotAllowDelete          = New400Response(400, "资源不允许删除")
	ErrInvalidUserName         = New400Response(400, "无效的用户名")
	ErrInvalidPassword         = New400Response(400, "无效的密码")
	ErrInvalidUser             = New400Response(400, "无效的用户")
	ErrUserDisable             = New400Response(400, "用户被禁用,请联系管理员")

	ErrNoPerm          = NewResponse(401, 401, nil, "无访问权限")
	ErrInvalidToken    = NewResponse(401, 401, nil, "令牌失效")
	ErrNotToken        = NewResponse(401, 401, nil, "未找到令牌")
	ErrNotFound        = WrapResponseWithField(fmt.Errorf("资源不存在"), 400, "", 100030002, nil, "资源不存在")
	ErrMethodNotAllow  = NewResponse(405, 405, nil, "方法不被允许")
	ErrTooManyRequests = NewResponse(429, 429, nil, "请求过于频繁")
	ErrInternalServer  = NewResponse(500, 500, nil, "服务器发生错误")
)

定义错误

Functions

func New400ErrResponse

func New400ErrResponse(code int, data interface{}, msg string, args ...interface{}) error

New400ErrResponse 创建错误码为400的响应错误

func New400ErrResponseWithField

func New400ErrResponseWithField(field string, code int, data interface{}, msg string, args ...interface{}) error

func New400Response

func New400Response(code int, msg string, args ...interface{}) error

func New400ResponseWithField

func New400ResponseWithField(field string, code int, msg string, args ...interface{}) error

func New500Error

func New500Error(code int, data interface{}) error

func New500Response

func New500Response(msg string, args ...interface{}) error

New500Response 创建错误码为500的响应错误

func NewError

func NewError(code int, err error) error

func NewErrorMsg

func NewErrorMsg(code int, err error, msg string, args ...interface{}) error

func NewMsg

func NewMsg(code int, msg string, args ...interface{}) error

func NewResError

func NewResError(err error) error

func NewResErrorMsg

func NewResErrorMsg(err error, msg string, a ...any) error

func NewResponse

func NewResponse(statusCode, code int, data interface{}, msg string, args ...interface{}) error

NewResponse 创建响应错误

func NewResponseWithField

func NewResponseWithField(statusCode int, field string, code int, data interface{}, msg string, args ...interface{}) error

NewResponseWithField 创建响应错误包含错误字段

func Wrap400Err

func Wrap400Err(err error, code int) error

func Wrap400ErrResponse

func Wrap400ErrResponse(err error, code int, data interface{}, msg string, args ...interface{}) error

Wrap400ErrResponse 包装错误码为400的响应错误

func Wrap400ErrWithField

func Wrap400ErrWithField(err error, field string, code int) error

func Wrap400Response

func Wrap400Response(err error, code int, msg string, args ...interface{}) error

Wrap400Response 包装错误码为400的响应错误

func Wrap400ResponseWithField

func Wrap400ResponseWithField(err error, field string, code int, data interface{}, msg string, args ...interface{}) error

func Wrap500Response

func Wrap500Response(err error, msg string, args ...interface{}) error

Wrap500Response 包装错误码为500的响应错误

func WrapField

func WrapField(err error, field string) error

func WrapResponse

func WrapResponse(err error, statusCode, code int, data interface{}, msg string, args ...interface{}) error

WrapResponse 包装响应错误

func WrapResponseWithField

func WrapResponseWithField(err error, statusCode int, field string, code int, data interface{}, msg string, args ...interface{}) error

WrapResponseWithField 包装响应错误

Types

type ResponseError

type ResponseError struct {
	Code       int         // 错误码
	Message    string      // 错误消息
	StatusCode int         // 响应状态码
	ERR        error       // 响应错误
	Field      string      // 错误字段
	Data       interface{} // 模版数据
}

ResponseError 定义响应错误

func UnWrapResponse

func UnWrapResponse(err error) *ResponseError

UnWrapResponse 解包响应错误

func (*ResponseError) Cause

func (r *ResponseError) Cause() error

func (*ResponseError) Error

func (r *ResponseError) Error() string

func (*ResponseError) Unwrap

func (r *ResponseError) Unwrap() error

Jump to

Keyboard shortcuts

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