go-create-error

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Go Error Generator

Go错误生成器

Generate typed custom errors for module-level
errs
packages.
为模块级
errs
包生成带类型的自定义错误。

Pattern

存放规则

Place errors in:
internal/modules/<module>/errs/errs.go
Each module error file follows:
  1. package errs
  2. Imports:
    • net/http
    • github.com/cristiano-pacheco/bricks/pkg/errs
  3. var (...)
    block with exported error variables
  4. Error creation via:
    • errs.New("<MODULE>_<NN>", "<Message>", http.<Status>, nil)
错误文件存放路径:
internal/modules/<module>/errs/errs.go
每个模块的错误文件需遵循以下规则:
  1. 声明包名为
    errs
  2. 导入依赖:
    • net/http
    • github.com/cristiano-pacheco/bricks/pkg/errs
  3. 使用
    var (...)
    块定义导出的错误变量
  4. 通过以下方式创建错误:
    • errs.New("<MODULE>_<NN>", "<Message>", http.<Status>, nil)

Example Structure

示例结构

go
package errs

import (
	"net/http"

	"github.com/cristiano-pacheco/bricks/pkg/errs"
)

var (
	// ErrInvalidContactType is returned when contact type is invalid.
	ErrInvalidContactType = errs.New("MONITOR_01", "Invalid contact type", http.StatusBadRequest, nil)
	// ErrContactNameAlreadyInUse is returned when contact name already exists.
	ErrContactNameAlreadyInUse = errs.New("MONITOR_02", "Contact name already in use", http.StatusConflict, nil)
)
go
package errs

import (
	"net/http"

	"github.com/cristiano-pacheco/bricks/pkg/errs"
)

var (
	// ErrInvalidContactType 当联系类型无效时返回。
	ErrInvalidContactType = errs.New("MONITOR_01", "Invalid contact type", http.StatusBadRequest, nil)
	// ErrContactNameAlreadyInUse 当联系名称已被使用时返回。
	ErrContactNameAlreadyInUse = errs.New("MONITOR_02", "Contact name already in use", http.StatusConflict, nil)
)

Generation Steps

生成步骤

  1. Identify error details:
    • Target module (
      identity
      ,
      monitor
      , ...)
    • Error variable name (
      ErrInvalidContactType
      )
    • Human message (
      "Invalid contact type"
      )
    • HTTP status (
      http.StatusBadRequest
      )
  2. Find the next code:
    • Open
      internal/modules/<module>/errs/errs.go
    • Extract existing codes for that module prefix
    • Allocate the next available code while preserving format:
      • IDENTITY_01
        ,
        IDENTITY_02
        , ...
      • MONITOR_01
        ,
        MONITOR_02
        , ...
    • Keep code uniqueness inside the module
  3. Add the new error:
    • Insert into the module
      var (...)
      block
    • Keep alphabetical or domain-group ordering used by the file
    • Prefer a short doc comment for consistency where comments are already used
  4. Validate usage path:
    • Ensure new/updated usecases, validators, handlers, or enum constructors return the new typed error
    • Do not return raw
      errors.New(...)
      from business flows when a typed module error exists
  1. 确定错误详情
    • 目标模块(
      identity
      monitor
      等)
    • 错误变量名(如
      ErrInvalidContactType
    • 用户友好提示信息(如
      "无效的联系类型"
    • HTTP状态码(如
      http.StatusBadRequest
  2. 确定下一个错误码
    • 打开
      internal/modules/<module>/errs/errs.go
      文件
    • 提取该模块前缀下已有的错误码
    • 按照现有格式分配下一个可用的错误码:
      • IDENTITY_01
        ,
        IDENTITY_02
        , ...
      • MONITOR_01
        ,
        MONITOR_02
        , ...
    • 确保同一模块内的错误码唯一
  3. 添加新错误
    • 将错误变量插入到模块的
      var (...)
      块中
    • 遵循文件已有的按字母顺序或领域分组的排序规则
    • 如果文件中已有注释,建议添加简短的文档注释以保持一致性
  4. 验证使用路径
    • 确保新增或更新的用例、验证器、处理器或枚举构造函数返回新的带类型错误
    • 当存在对应的模块带类型错误时,业务流程中不要返回原生的
      errors.New(...)
      错误

Naming Conventions

命名规范

  • Variable:
    Err
    + clear domain phrase in PascalCase
    • Example:
      ErrInvalidUserStatus
      ,
      ErrOAuthStateNotFound
  • Code:
    <MODULE>_<NN>
    • IDENTITY_54
      ,
      MONITOR_05
  • Message:
    • Short, user-safe, sentence case
    • Start with uppercase letter
    • Avoid punctuation unless needed
  • HTTP status:
    • Validation errors:
      http.StatusBadRequest
    • Auth failures:
      http.StatusUnauthorized
      /
      http.StatusForbidden
    • Missing resources:
      http.StatusNotFound
    • Conflicts:
      http.StatusConflict
    • Rate limit:
      http.StatusTooManyRequests
    • Infra/internal failures:
      http.StatusInternalServerError
      /
      http.StatusServiceUnavailable
  • 变量命名
    Err
    开头,后跟清晰的领域相关短语,采用大驼峰命名法
    • 示例:
      ErrInvalidUserStatus
      ,
      ErrOAuthStateNotFound
  • 错误码:格式为
    <MODULE>_<NN>
    • 示例:
      IDENTITY_54
      ,
      MONITOR_05
  • 错误信息
    • 简洁、对用户友好,首字母大写的句子格式
    • 首字母大写
    • 除非必要,否则不要使用标点符号
  • HTTP状态码
    • 验证错误:
      http.StatusBadRequest
    • 认证失败:
      http.StatusUnauthorized
      /
      http.StatusForbidden
    • 资源不存在:
      http.StatusNotFound
    • 资源冲突:
      http.StatusConflict
    • 请求限流:
      http.StatusTooManyRequests
    • 基础设施/内部错误:
      http.StatusInternalServerError
      /
      http.StatusServiceUnavailable

Implementation Checklist

实施检查清单

  • Open target
    internal/modules/<module>/errs/errs.go
  • Compute next unique module code
  • Add exported
    Err...
    variable with
    errs.New(...)
  • Match existing ordering/grouping style
  • Ensure message and status align with domain behavior
  • Replace raw error returns in calling code with typed
    errs.Err...
    where applicable
  • 打开目标文件
    internal/modules/<module>/errs/errs.go
  • 计算下一个唯一的模块错误码
  • 使用
    errs.New(...)
    添加导出的
    Err...
    变量
  • 与现有排序/分组风格保持一致
  • 确保错误信息和状态码与领域行为匹配
  • 在适用的场景下,将调用代码中返回的原生错误替换为带类型的
    errs.Err...

Usage Pattern

使用示例

go
if input.RedirectURI == "" {
	return errs.ErrInvalidRedirectURI
}

if user == nil {
	return errs.ErrUserNotFound
}
go
if input.RedirectURI == "" {
	return errs.ErrInvalidRedirectURI
}

if user == nil {
	return errs.ErrUserNotFound
}

Critical Rules

核心规则

  • Do not create a new error package; use module-local
    internal/modules/<module>/errs
  • Do not duplicate codes within the same module
  • Do not return persistence or infrastructure-specific raw errors to transport when a typed domain error exists
  • Keep error messages stable once exposed, unless migration/compatibility impact is accepted
  • 不要创建新的错误包,使用模块本地的
    internal/modules/<module>/errs
  • 同一模块内不要重复使用错误码
  • 当存在对应的领域带类型错误时,不要将持久层或基础设施相关的原生错误返回给传输层
  • 错误信息一旦对外暴露,需保持稳定,除非已接受迁移/兼容性影响