Documentation
¶
Overview ¶
Package code demonstrates how to define error codes for a project. This is an example file showing the recommended error code organization pattern.
Error Code Structure: - Format: SSSMMM (SSS=Service ID 3位, MMM=Module ID 3位) - Service ID 10: Common base errors (0base.go) - Service ID 11: Proxy claim service (1proxy_claim.go) - Service ID 12: Proxy controller service (2proxy_controller.go)
Usage:
// Generate code and documentation go generate // Use in your code err := errors.WithCode(code.Namespace, ErrNotFound, "resource %s not found", id)
Package code demonstrates how to define error codes for a project. This is an example file showing the recommended error code organization pattern.
The error code design follows the SSSMMM pattern:
SSS - Service ID (3 digits) MMM - Module ID (3 digits)
Error codes are grouped by services and modules for better organization.
Allowed HTTP status codes:
StatusOK = 200 // RFC 7231, 6.3.1 StatusBadRequest = 400 // RFC 7231, 6.5.1 StatusUnauthorized = 401 // RFC 7235, 3.1 StatusForbidden = 403 // RFC 7231, 6.5.3 StatusNotFound = 404 // RFC 7231, 6.5.4 StatusRequestTimeout = 408 // RFC 7231, 6.5.7 StatusConflict = 409 // RFC 7231, 6.5.8 StatusTooManyRequests = 429 // RFC 6585, 4 StatusInternalServerError = 500 // RFC 7231, 6.6.1
Error Code Structure:
Service ID 10: Common base errors (0base.go) Service ID 11: Proxy claim service (1proxy_claim.go) Service ID 12: Proxy controller service (2proxy_controller.go)
Usage:
// Generate code and documentation
go generate
// Use in your code
err := errors.WithCode("example", ErrNotFound, "resource %s not found", id)
Package code demonstrates how to use error codes and wrapper functions.
Index ¶
- Constants
- func AggregateGoroutines(funcs ...func() error) errors.Aggregate
- func As(err error, target interface{}) bool
- func Cause(err error) error
- func Errorf(format string, args ...interface{}) error
- func ExampleAggregateGoroutines()
- func ExampleAllErrorCodes()
- func ExampleCause()
- func ExampleErrorChain()
- func ExampleErrorDetails()
- func ExampleErrorWithReference()
- func ExampleErrorf()
- func ExampleFilterOut()
- func ExampleFlatten()
- func ExampleMultipleErrors()
- func ExampleNamespace()
- func ExampleNew()
- func ExampleNewAggregate()
- func ExampleReduce()
- func ExampleWithCode()
- func ExampleWithMessage()
- func ExampleWithMessagef()
- func ExampleWithStack()
- func ExampleWrap()
- func ExampleWrapC()
- func ExampleWrapf()
- func FilterOut(err error, fns ...errors.Matcher) error
- func Flatten(agg errors.Aggregate) errors.Aggregate
- func Is(err, target error) bool
- func IsCode(err error, code int) bool
- func New(message string) error
- func NewAggregate(errlist []error) errors.Aggregate
- func Reduce(err error) error
- func Unwrap(err error) error
- func WithCode(code int, format string, args ...interface{}) error
- func WithMessage(err error, message string) error
- func WithMessagef(err error, format string, args ...interface{}) error
- func WithStack(err error) error
- func Wrap(err error, message string) error
- func WrapC(err error, code int, format string, args ...interface{}) error
- func Wrapf(err error, format string, args ...interface{}) error
Constants ¶
const ( // ErrSuccess - 200: OK. // Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/success.md ErrSuccess int = iota + 100001 // ErrUnknown - 500: Contact system administrator with error details for investigation. // Reference Message: Internal server error occurred, check logs for details // Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/unknown.md ErrUnknown // ErrBind - 400: Check request body and ensure it matches the expected format. // Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/bind.md ErrBind // ErrValidation - 400: Check input parameters and ensure they meet validation requirements. // Reference Message: Input validation failed, check parameter constraints ErrValidation // ErrTokenInvalid - 401: Provide a valid authentication token. ErrTokenInvalid // ErrPageNotFound - 404: Check the URL path and try again. ErrPageNotFound // ErrRequestTimeout - 408: Retry request or check network connection. // Reference Message: Request timeout, check network connectivity and retry ErrRequestTimeout // ErrInvalidParameter - 400: Check input parameters and ensure they are valid. ErrInvalidParameter )
Common: basic errors. Code must start with 100001. Refer to https://github.com/ClessLi/component-base/pkg/errors for details. Service ID: 10, Module ID: 00
const ( // ErrEncrypt - 401: Provide a valid password that can be encrypted. ErrEncrypt int = iota + 100301 // ErrSignatureInvalid - 401: Provide a request with valid signature. ErrSignatureInvalid // ErrExpired - 401: Refresh authentication token and try again. ErrExpired // ErrInvalidAuthHeader - 401: Provide request with valid authorization header. ErrInvalidAuthHeader // ErrMissingHeader - 401: Provide request with valid Authorization header. ErrMissingHeader // ErrUserOrPasswordIncorrect - 401: Provide valid username and password credentials. ErrUserOrPasswordIncorrect // ErrPermissionDenied - 403: Contact system administrator for required permissions. ErrPermissionDenied // ErrAuthnClientInitFailed - 500: Contact system administrator to initialize authentication client. ErrAuthnClientInitFailed // ErrAuthClientNotInit - 500: Contact system administrator to initialize authentication and authorization clients. ErrAuthClientNotInit // ErrConnToAuthServerFailed - 500: Contact system administrator to check authentication server connectivity. ErrConnToAuthServerFailed )
Common: authorization and authentication errors. Code must start with 100301. Service ID: 10, Module ID: 03
const ( // ErrEncodingFailed - 500: Check data format and ensure it can be properly encoded. // Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/encoding.md ErrEncodingFailed int = iota + 100401 // ErrDecodingFailed - 500: Check data format and ensure it can be properly decoded. ErrDecodingFailed // ErrInvalidJSON - 500: Provide data in valid JSON format. ErrInvalidJSON // ErrEncodingJSON - 500: Check JSON data and ensure it can be properly encoded. ErrEncodingJSON // ErrDecodingJSON - 500: Check JSON data and ensure it can be properly decoded. ErrDecodingJSON // ErrInvalidYaml - 500: Provide data in valid YAML format. ErrInvalidYaml // ErrEncodingYaml - 500: Check YAML data and ensure it can be properly encoded. ErrEncodingYaml // ErrDecodingYaml - 500: Check YAML data and ensure it can be properly decoded. ErrDecodingYaml )
Common: encode/decode errors. Code must start with 100401. Service ID: 10, Module ID: 04
const ( // ErrDatabase - 500: Contact system administrator to resolve database connectivity issue. // Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/database.md ErrDatabase int = iota + 100101 )
Common: database errors. Code must start with 100101. Service ID: 10, Module ID: 01
const Namespace = "codeexample"
Namespace is the error code namespace for this package.
Variables ¶
This section is empty.
Functions ¶
func AggregateGoroutines ¶
AggregateGoroutines runs the provided functions in parallel, stuffing all non-nil errors into the returned Aggregate.
Example:
agg := AggregateGoroutines(
func() error { return doWork1() },
func() error { return doWork2() },
)
if agg != nil {
fmt.Println(agg)
}
func As ¶
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
Example:
var target *CustomError
if As(err, &target) {
fmt.Println(target.Message)
}
func Cause ¶
Cause returns the underlying cause of the error.
Example:
cause := Cause(wrappedErr)
fmt.Println(cause) // Output: root cause message
fmt.Printf("%+v\n", cause) // Output: root cause message - stack trace details
func Errorf ¶
Errorf formats according to a format specifier and returns the string as a value that satisfies error. Errorf also records the stack trace at the point it was called.
Example:
err := Errorf("connection timeout after %d seconds", 30)
fmt.Println(err) // Output: connection timeout after 30 seconds
fmt.Printf("%+v\n", err) // Output: connection timeout after 30 seconds - stack trace details
func ExampleAggregateGoroutines ¶
func ExampleAggregateGoroutines()
ExampleAggregateGoroutines demonstrates aggregating errors from goroutines.
Example output:
Aggregated errors collected
func ExampleAllErrorCodes ¶
func ExampleAllErrorCodes()
ExampleAllErrorCodes demonstrates all defined error codes.
Note: This example iterates through all defined error codes and displays their external messages. Useful for verifying all error codes are properly registered.
Example output:
Code 100001: OK Code 100002: Contact system administrator with error details for investigation Code 100003: Check request body and ensure it matches the expected format ... (and more error codes)
func ExampleCause ¶
func ExampleCause()
ExampleCause demonstrates retrieving the root cause of error.
Note: Cause returns the underlying cause of the error chain. For wrapped errors, this returns the original error that started the chain.
Example output:
disk full
func ExampleErrorChain ¶
func ExampleErrorChain()
ExampleErrorChain demonstrates error chain handling.
Note: Shows how errors are chained and how Cause retrieves the root cause. Wrap preserves the original error in the chain.
Example output:
Root cause: database connection failed Full error: service unavailable
func ExampleErrorDetails ¶
func ExampleErrorDetails()
ExampleErrorDetails demonstrates extracting detailed error information.
This example shows how to extract all error details including: - Namespace: The error code namespace - Code: The numeric error code - HTTPStatus: The HTTP status code - Ext: The external (user-safe) error message - Reference: The reference URL for documentation
func ExampleErrorWithReference ¶
func ExampleErrorWithReference()
ExampleErrorWithReference demonstrates error with reference URL.
Note: Shows how errors display their external messages. The reference URL is stored internally and can be accessed via errors.ParseCoder().
Example output:
Error: Contact system administrator with error details for investigation Error: Check request body and ensure it matches the expected format
func ExampleErrorf ¶
func ExampleErrorf()
ExampleErrorf demonstrates creating formatted errors.
Note: Errorf creates a plain formatted error without error code, similar to fmt.Errorf. It records a stack trace at the point it was called.
Example output:
connection timeout after 30 seconds
func ExampleFilterOut ¶
func ExampleFilterOut()
ExampleFilterOut demonstrates filtering errors from an aggregate.
Note: FilterOut removes errors matching specified criteria from the aggregate. The remaining errors are returned as a new aggregate.
Example output:
Filtered: Contact system administrator to resolve database connectivity issue
func ExampleFlatten ¶
func ExampleFlatten()
ExampleFlatten demonstrates flattening nested aggregates.
Example output:
Flattened count: 3
func ExampleMultipleErrors ¶
func ExampleMultipleErrors()
ExampleMultipleErrors demonstrates handling multiple error codes.
Note: Each error displays its external message (Ext field), which is the user-safe message mapped to the error code.
Example output:
Error: OK Error: Check the URL path and try again Error: Check input parameters and ensure they meet validation requirements Error: Contact system administrator to resolve database connectivity issue
func ExampleNamespace ¶
func ExampleNamespace()
ExampleNamespace demonstrates namespace isolation.
Note: The namespace is automatically injected from the code package and ensures error codes are isolated across different projects.
Example output:
Namespace: codeexample Error namespace: codeexample Error code: 100001
func ExampleNew ¶
func ExampleNew()
ExampleNew demonstrates creating simple errors.
Note: New creates a plain error without error code, similar to fmt.Errorf. It records a stack trace at the point it was called.
Example output:
invalid email format
func ExampleNewAggregate ¶
func ExampleNewAggregate()
ExampleNewAggregate demonstrates creating an aggregate of errors.
Note: Multiple errors are combined into a single Aggregate interface. The output shows all external messages joined together in brackets.
Example output:
[Check the URL path and try again, Contact system administrator to resolve database connectivity issue]
func ExampleReduce ¶
func ExampleReduce()
ExampleReduce demonstrates reducing an aggregate to a single error.
Example output:
Reduced: OK
func ExampleWithCode ¶
func ExampleWithCode()
ExampleWithCode demonstrates creating errors with code using wrapper function.
Note: The output shows the error code's external message (Ext field), not the custom message passed to WithCode. Use %+v to see full error details.
Example output:
Check the URL path and try again Error details: user 12345 not found - #0 (codeexample:100006) Check the URL path and try again
func ExampleWithMessage ¶
func ExampleWithMessage()
ExampleWithMessage demonstrates adding message to error.
Note: Unlike other functions, WithMessage replaces the external message with the provided message, making it suitable for user-facing error messages.
Example output:
failed to parse request body
func ExampleWithMessagef ¶
func ExampleWithMessagef()
ExampleWithMessagef demonstrates adding formatted message to error.
Note: Unlike other functions, WithMessagef replaces the external message with the formatted message, making it suitable for user-facing error messages.
Example output:
failed to encode JSON response
func ExampleWithStack ¶
func ExampleWithStack()
ExampleWithStack demonstrates adding stack trace to error.
Note: The output shows the error code's external message (Ext field). The stack trace is included when using %+v format for detailed debugging.
Example output:
Contact system administrator with error details for investigation
func ExampleWrap ¶
func ExampleWrap()
ExampleWrap demonstrates wrapping errors with context.
Note: Wrap annotates the original error with a new message and adds a stack trace. The original error is preserved in the error chain.
Example output:
failed to connect to database
func ExampleWrapC ¶
func ExampleWrapC()
ExampleWrapC demonstrates wrapping errors with code and namespace.
Note: The output shows the error code's external message (Ext field), not the custom message passed to WrapC. The namespace is automatically injected.
Example output:
Provide a valid authentication token
func ExampleWrapf ¶
func ExampleWrapf()
ExampleWrapf demonstrates wrapping errors with formatted message.
Note: Wrapf annotates the original error with a formatted message and adds a stack trace. The original error is preserved in the error chain.
Example output:
failed to write data to /var/log
func FilterOut ¶
FilterOut removes all errors that match any of the matchers from the input error.
Example:
filtered := FilterOut(agg, func(err error) bool {
return IsCode(err, ErrPageNotFound)
})
fmt.Println(filtered)
func Flatten ¶
Flatten takes an Aggregate and flattens them all into a single Aggregate, recursively.
Example:
flattened := Flatten(nestedAgg) fmt.Println(flattened)
func Is ¶
Is reports whether any error in err's chain matches target.
Example:
if Is(err, io.EOF) {
fmt.Println("End of stream")
}
func IsCode ¶
IsCode reports whether any error in err's chain contains the given error code within the specified namespace.
Example:
if IsCode(err, ErrPageNotFound) {
fmt.Println("Page not found")
}
func New ¶
New returns an error with the supplied message. New also records the stack trace at the point it was called.
Example:
err := New("invalid email format")
fmt.Println(err) // Output: invalid email format
fmt.Printf("%+v\n", err) // Output: invalid email format - stack trace details
func NewAggregate ¶
NewAggregate converts a slice of errors into an Aggregate interface.
Example:
agg := NewAggregate([]error{err1, err2})
fmt.Println(agg) // Output: [error1 message, error2 message]
fmt.Printf("%+v\n", agg) // Output: [error1 details, error2 details]
func Reduce ¶
Reduce will return err or, if err is an Aggregate and only has one item, the first item.
Example:
reduced := Reduce(agg) fmt.Println(reduced)
func Unwrap ¶
Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.
Example:
unwrapped := Unwrap(wrappedErr) fmt.Println(unwrapped)
func WithCode ¶
WithCode creates an error with code and auto-injected namespace.
Example:
err := WithCode(ErrPageNotFound, "user %s not found", "12345")
fmt.Println(err) // Output: Check the URL path and try again
fmt.Printf("%+v\n", err) // Output: user 12345 not found - #0 (codeexample:100006) Check the URL path and try again
func WithMessage ¶
WithMessage annotates err with a new message.
Example:
err := WithMessage(originalErr, "failed to parse request body")
fmt.Println(err) // Output: failed to parse request body
fmt.Printf("%+v\n", err) // Output: failed to parse request body - stack trace details
func WithMessagef ¶
WithMessagef annotates err with a formatted message.
Example:
err := WithMessagef(originalErr, "failed to encode %s response", "JSON")
fmt.Println(err) // Output: failed to encode JSON response
fmt.Printf("%+v\n", err) // Output: failed to encode JSON response - stack trace details
func WithStack ¶
WithStack annotates err with a stack trace.
Example:
err := WithStack(originalErr)
fmt.Println(err) // Output: original error message
fmt.Printf("%+v\n", err) // Output: original error message - stack trace details
func Wrap ¶
Wrap returns an error annotating err with a stack trace at the point Wrap is called, and the supplied message.
Example:
err := Wrap(originalErr, "failed to connect to database")
fmt.Println(err) // Output: failed to connect to database
fmt.Printf("%+v\n", err) // Output: failed to connect to database - stack trace details
func WrapC ¶
WrapC wraps an error with code and auto-injected namespace.
Example:
err := WrapC(originalErr, ErrDatabase, "failed to connect to %s", "db")
fmt.Println(err) // Output: Contact system administrator to resolve database connectivity issue
fmt.Printf("%+v\n", err) // Output: failed to connect to db - #0 (codeexample:100007) Contact system administrator to resolve database connectivity issue
func Wrapf ¶
Wrapf returns an error annotating err with a stack trace at the point Wrapf is called, and the format specifier.
Example:
err := Wrapf(originalErr, "failed to write to %s", "/var/log")
fmt.Println(err) // Output: failed to write to /var/log
fmt.Printf("%+v\n", err) // Output: failed to write to /var/log - stack trace details
Types ¶
This section is empty.