errorx(error code management)

Comprehensive error code management with status codes, stack traces, and configurable error registration for structured error handling.

The errorx module provides comprehensive error code management with status codes, stack traces, and configurable error registration for structured error handling.

Features

  • Status code support for errors
  • Automatic stack trace generation
  • Error registration with templates
  • Flexible key-value parameters
  • Stability tracking for system errors
  • Error wrapping capabilities
  • Code generation tool for automatic error code registration

Code Generation

The errorx module includes a powerful code generator (errorx/gen) that automatically generates code.Register calls from YAML configuration files. This approach ensures consistency and reduces manual coding errors.

Setting up Code Generation

  1. Create metadata configuration (metadata.yaml):
 1version: 'v1'
 2
 3error_code:
 4  # Total length of the error code (default: 9)
 5  total_length: 6
 6  # Length of app code (default: 1)
 7  app_length: 1
 8  # Length of business code (default: 3)
 9  biz_length: 2
10  # Length of sub code (default: 4)
11  sub_length: 3
12
13app:
14  - name: myapp
15    code: 6  # App identifier (1-9)
16    business:
17      - name: common
18        code: 0
19      - name: user
20        code: 10
21      - name: order
22        code: 20
  1. Create common error codes (common.yaml):
 1error_code:
 2  - name: CommonNoPermission
 3    code: 101
 4    message: no access permission
 5    no_affect_stability: true
 6
 7  - name: CommonInternalError
 8    code: 500
 9    message: internal server error
10    no_affect_stability: false
  1. Create business-specific error codes (user.yaml):
 1error_code:
 2  - name: UserNotFound
 3    code: 1001
 4    message: user not found
 5    description: the specified user does not exist
 6    no_affect_stability: true
 7
 8  - name: UserAlreadyExists
 9    code: 1002
10    message: user already exists
11    no_affect_stability: true

Generate Code

Run the generator to create Go code with error registrations:

1go run github.com/crazyfrankie/frx/errorx/gen/code_gen.go \
2     --biz user \
3     --app-name myapp \
4     --app-code 6 \
5     --import-path "github.com/crazyfrankie/frx/errorx/code" \
6     --output-dir "./generated/user" \
7     --script-dir "./config"

This generates Go files with automatic error code registration:

 1// Generated code
 2package errno
 3
 4import "github.com/crazyfrankie/frx/errorx/code"
 5
 6const (
 7    UserNotFound = int32(610001001)
 8    UserAlreadyExists = int32(610001002)
 9)
10
11func init() {
12    code.Register(UserNotFound, "user not found", code.WithAffectStability(false))
13    code.Register(UserAlreadyExists, "user already exists", code.WithAffectStability(false))
14}

Manual Registration (Alternative)

You can also manually register error codes:

 1package errno
 2
 3import "github.com/crazyfrankie/frx/errorx/code"
 4
 5const (
 6    ErrPermissionDenied = int32(1000001)
 7    ErrResourceNotFound = int32(1000002)
 8    ErrInvalidParameter = int32(1000003)
 9)
10
11func init() {
12    code.Register(
13        ErrPermissionDenied,
14        "unauthorized access: {user}",
15        code.WithAffectStability(false),
16    )
17    
18    code.Register(
19        ErrResourceNotFound,
20        "resource not found: {resource}",
21        code.WithAffectStability(true),
22    )
23}

Using Generated or Registered Errors

Then use the errors in your application:

 1package main
 2
 3import (
 4    "fmt"
 5	
 6    "github.com/crazyfrankie/frx/errorx"
 7    
 8	"your-project/types/errno"
 9)
10
11func main() {
12    // Create new error with parameters
13    err := errorx.New(errno.ErrPermissionDenied, 
14        errorx.KV("user", "john_doe"),
15        errorx.Extra("request_id", "req-123"),
16    )
17    
18    // Wrap existing error
19    originalErr := fmt.Errorf("database connection failed")
20    wrappedErr := errorx.WrapByCode(originalErr, errno.ErrResourceNotFound,
21        errorx.KV("resource", "user_table"),
22    )
23    
24    // Extract error information
25    if statusErr, ok := err.(errorx.StatusError); ok {
26        fmt.Printf("Code: %d\n", statusErr.Code())
27        fmt.Printf("Message: %s\n", statusErr.Msg())
28        fmt.Printf("Affects Stability: %v\n", statusErr.IsAffectStability())
29    }
30}