{"modulePath":"github.com/ClessLi/component-base","version":"v1.0.14","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package code\n\nPackage code demonstrates how to define error codes for a project. This is an example file showing the recommended error code organization pattern.\n\nError 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)\n\nUsage:\n\n\t// Generate code and documentation\n\tgo generate\n\n\t// Use in your code\n\terr := errors.WithCode(code.Namespace, ErrNotFound, \"resource %s not found\", id)\n\nPackage code demonstrates how to define error codes for a project. This is an example file showing the recommended error code organization pattern.\n\nThe error code design follows the SSSMMM pattern:\n\n\tSSS - Service ID (3 digits)\n\tMMM - Module ID (3 digits)\n\nError codes are grouped by services and modules for better organization.\n\nAllowed HTTP status codes:\n\n\tStatusOK                  = 200 // RFC 7231, 6.3.1\n\tStatusBadRequest          = 400 // RFC 7231, 6.5.1\n\tStatusUnauthorized        = 401 // RFC 7235, 3.1\n\tStatusForbidden           = 403 // RFC 7231, 6.5.3\n\tStatusNotFound            = 404 // RFC 7231, 6.5.4\n\tStatusRequestTimeout      = 408 // RFC 7231, 6.5.7\n\tStatusConflict            = 409 // RFC 7231, 6.5.8\n\tStatusTooManyRequests     = 429 // RFC 6585, 4\n\tStatusInternalServerError = 500 // RFC 7231, 6.6.1\n\nError Code Structure:\n\n\tService ID 10: Common base errors (0base.go)\n\tService ID 11: Proxy claim service (1proxy_claim.go)\n\tService ID 12: Proxy controller service (2proxy_controller.go)\n\nUsage:\n\n\t// Generate code and documentation\n\tgo generate\n\n\t// Use in your code\n\terr := errors.WithCode(\"example\", ErrNotFound, \"resource %s not found\", id)\n\nPackage code demonstrates how to use error codes and wrapper functions.\n\n## Constants\n\n```go\nconst (\n\t// ErrSuccess - 200: OK.\n\t// Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/success.md\n\tErrSuccess int = iota + 100001\n\n\t// ErrUnknown - 500: Contact system administrator with error details for investigation.\n\t// Reference Message: Internal server error occurred, check logs for details\n\t// Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/unknown.md\n\tErrUnknown\n\n\t// ErrBind - 400: Check request body and ensure it matches the expected format.\n\t// Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/bind.md\n\tErrBind\n\n\t// ErrValidation - 400: Check input parameters and ensure they meet validation requirements.\n\t// Reference Message: Input validation failed, check parameter constraints\n\tErrValidation\n\n\t// ErrTokenInvalid - 401: Provide a valid authentication token.\n\tErrTokenInvalid\n\n\t// ErrPageNotFound - 404: Check the URL path and try again.\n\tErrPageNotFound\n\n\t// ErrRequestTimeout - 408: Retry request or check network connection.\n\t// Reference Message: Request timeout, check network connectivity and retry\n\tErrRequestTimeout\n\n\t// ErrInvalidParameter - 400: Check input parameters and ensure they are valid.\n\tErrInvalidParameter\n)\n```\nCommon: basic errors. Code must start with 100001. Refer to [https://github.com/ClessLi/component-base/pkg/errors](https://github.com/ClessLi/component-base/pkg/errors) for details. Service ID: 10, Module ID: 00\n\n```go\nconst (\n\t// ErrEncrypt - 401: Provide a valid password that can be encrypted.\n\tErrEncrypt int = iota + 100301\n\n\t// ErrSignatureInvalid - 401: Provide a request with valid signature.\n\tErrSignatureInvalid\n\n\t// ErrExpired - 401: Refresh authentication token and try again.\n\tErrExpired\n\n\t// ErrInvalidAuthHeader - 401: Provide request with valid authorization header.\n\tErrInvalidAuthHeader\n\n\t// ErrMissingHeader - 401: Provide request with valid Authorization header.\n\tErrMissingHeader\n\n\t// ErrUserOrPasswordIncorrect - 401: Provide valid username and password credentials.\n\tErrUserOrPasswordIncorrect\n\n\t// ErrPermissionDenied - 403: Contact system administrator for required permissions.\n\tErrPermissionDenied\n\n\t// ErrAuthnClientInitFailed - 500: Contact system administrator to initialize authentication client.\n\tErrAuthnClientInitFailed\n\n\t// ErrAuthClientNotInit - 500: Contact system administrator to initialize authentication and authorization clients.\n\tErrAuthClientNotInit\n\n\t// ErrConnToAuthServerFailed - 500: Contact system administrator to check authentication server connectivity.\n\tErrConnToAuthServerFailed\n)\n```\nCommon: authorization and authentication errors. Code must start with 100301. Service ID: 10, Module ID: 03\n\n```go\nconst (\n\t// ErrEncodingFailed - 500: Check data format and ensure it can be properly encoded.\n\t// Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/encoding.md\n\tErrEncodingFailed int = iota + 100401\n\n\t// ErrDecodingFailed - 500: Check data format and ensure it can be properly decoded.\n\tErrDecodingFailed\n\n\t// ErrInvalidJSON - 500: Provide data in valid JSON format.\n\tErrInvalidJSON\n\n\t// ErrEncodingJSON - 500: Check JSON data and ensure it can be properly encoded.\n\tErrEncodingJSON\n\n\t// ErrDecodingJSON - 500: Check JSON data and ensure it can be properly decoded.\n\tErrDecodingJSON\n\n\t// ErrInvalidYaml - 500: Provide data in valid YAML format.\n\tErrInvalidYaml\n\n\t// ErrEncodingYaml - 500: Check YAML data and ensure it can be properly encoded.\n\tErrEncodingYaml\n\n\t// ErrDecodingYaml - 500: Check YAML data and ensure it can be properly decoded.\n\tErrDecodingYaml\n)\n```\nCommon: encode/decode errors. Code must start with 100401. Service ID: 10, Module ID: 04\n\n```go\nconst (\n\t// ErrDatabase - 500: Contact system administrator to resolve database connectivity issue.\n\t// Reference: https://github.com/ClessLi/component-base/blob/main/docs/guide/zh-CN/errors/database.md\n\tErrDatabase int = iota + 100101\n)\n```\nCommon: database errors. Code must start with 100101. Service ID: 10, Module ID: 01\n\n```go\nconst Namespace = \"codeexample\"\n```\nNamespace is the error code namespace for this package.\n\n## Functions\n\n```go\nfunc AggregateGoroutines(funcs ...func() error) errors.Aggregate\n```\nAggregateGoroutines runs the provided functions in parallel, stuffing all non-nil errors into the returned Aggregate.\n\nExample:\n\n\tagg := AggregateGoroutines(\n\t\tfunc() error { return doWork1() },\n\t\tfunc() error { return doWork2() },\n\t)\n\tif agg != nil {\n\t\tfmt.Println(agg)\n\t}\n\n```go\nfunc As(err error, target interface{}) bool\n```\nAs finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.\n\nExample:\n\n\tvar target *CustomError\n\tif As(err, \u0026target) {\n\t\tfmt.Println(target.Message)\n\t}\n\n```go\nfunc Cause(err error) error\n```\nCause returns the underlying cause of the error.\n\nExample:\n\n\tcause := Cause(wrappedErr)\n\tfmt.Println(cause)          // Output: root cause message\n\tfmt.Printf(\"%+v\\n\", cause) // Output: root cause message - stack trace details\n\n```go\nfunc Errorf(format string, args ...interface{}) error\n```\nErrorf 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.\n\nExample:\n\n\terr := Errorf(\"connection timeout after %d seconds\", 30)\n\tfmt.Println(err)          // Output: connection timeout after 30 seconds\n\tfmt.Printf(\"%+v\\n\", err) // Output: connection timeout after 30 seconds - stack trace details\n\n```go\nfunc ExampleAggregateGoroutines()\n```\nExampleAggregateGoroutines demonstrates aggregating errors from goroutines.\n\nExample output:\n\n\tAggregated errors collected\n\n```go\nfunc ExampleAllErrorCodes()\n```\nExampleAllErrorCodes demonstrates all defined error codes.\n\nNote: This example iterates through all defined error codes and displays their external messages. Useful for verifying all error codes are properly registered.\n\nExample output:\n\n\tCode 100001: OK\n\tCode 100002: Contact system administrator with error details for investigation\n\tCode 100003: Check request body and ensure it matches the expected format\n\t... (and more error codes)\n\n```go\nfunc ExampleCause()\n```\nExampleCause demonstrates retrieving the root cause of error.\n\nNote: Cause returns the underlying cause of the error chain. For wrapped errors, this returns the original error that started the chain.\n\nExample output:\n\n\tdisk full\n\n```go\nfunc ExampleErrorChain()\n```\nExampleErrorChain demonstrates error chain handling.\n\nNote: Shows how errors are chained and how Cause retrieves the root cause. Wrap preserves the original error in the chain.\n\nExample output:\n\n\tRoot cause: database connection failed\n\tFull error: service unavailable\n\n```go\nfunc ExampleErrorDetails()\n```\nExampleErrorDetails demonstrates extracting detailed error information.\n\nThis 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\n\n```go\nfunc ExampleErrorWithReference()\n```\nExampleErrorWithReference demonstrates error with reference URL.\n\nNote: Shows how errors display their external messages. The reference URL is stored internally and can be accessed via errors.ParseCoder().\n\nExample output:\n\n\tError: Contact system administrator with error details for investigation\n\tError: Check request body and ensure it matches the expected format\n\n```go\nfunc ExampleErrorf()\n```\nExampleErrorf demonstrates creating formatted errors.\n\nNote: Errorf creates a plain formatted error without error code, similar to fmt.Errorf. It records a stack trace at the point it was called.\n\nExample output:\n\n\tconnection timeout after 30 seconds\n\n```go\nfunc ExampleFilterOut()\n```\nExampleFilterOut demonstrates filtering errors from an aggregate.\n\nNote: FilterOut removes errors matching specified criteria from the aggregate. The remaining errors are returned as a new aggregate.\n\nExample output:\n\n\tFiltered: Contact system administrator to resolve database connectivity issue\n\n```go\nfunc ExampleFlatten()\n```\nExampleFlatten demonstrates flattening nested aggregates.\n\nExample output:\n\n\tFlattened count: 3\n\n```go\nfunc ExampleMultipleErrors()\n```\nExampleMultipleErrors demonstrates handling multiple error codes.\n\nNote: Each error displays its external message (Ext field), which is the user-safe message mapped to the error code.\n\nExample output:\n\n\tError: OK\n\tError: Check the URL path and try again\n\tError: Check input parameters and ensure they meet validation requirements\n\tError: Contact system administrator to resolve database connectivity issue\n\n```go\nfunc ExampleNamespace()\n```\nExampleNamespace demonstrates namespace isolation.\n\nNote: The namespace is automatically injected from the code package and ensures error codes are isolated across different projects.\n\nExample output:\n\n\tNamespace: codeexample\n\tError namespace: codeexample\n\tError code: 100001\n\n```go\nfunc ExampleNew()\n```\nExampleNew demonstrates creating simple errors.\n\nNote: New creates a plain error without error code, similar to fmt.Errorf. It records a stack trace at the point it was called.\n\nExample output:\n\n\tinvalid email format\n\n```go\nfunc ExampleNewAggregate()\n```\nExampleNewAggregate demonstrates creating an aggregate of errors.\n\nNote: Multiple errors are combined into a single Aggregate interface. The output shows all external messages joined together in brackets.\n\nExample output:\n\n\t[Check the URL path and try again, Contact system administrator to resolve database connectivity issue]\n\n```go\nfunc ExampleReduce()\n```\nExampleReduce demonstrates reducing an aggregate to a single error.\n\nExample output:\n\n\tReduced: OK\n\n```go\nfunc ExampleWithCode()\n```\nExampleWithCode demonstrates creating errors with code using wrapper function.\n\nNote: 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.\n\nExample output:\n\n\tCheck the URL path and try again\n\tError details: user 12345 not found - #0 (codeexample:100006) Check the URL path and try again\n\n```go\nfunc ExampleWithMessage()\n```\nExampleWithMessage demonstrates adding message to error.\n\nNote: Unlike other functions, WithMessage replaces the external message with the provided message, making it suitable for user-facing error messages.\n\nExample output:\n\n\tfailed to parse request body\n\n```go\nfunc ExampleWithMessagef()\n```\nExampleWithMessagef demonstrates adding formatted message to error.\n\nNote: Unlike other functions, WithMessagef replaces the external message with the formatted message, making it suitable for user-facing error messages.\n\nExample output:\n\n\tfailed to encode JSON response\n\n```go\nfunc ExampleWithStack()\n```\nExampleWithStack demonstrates adding stack trace to error.\n\nNote: The output shows the error code's external message (Ext field). The stack trace is included when using %+v format for detailed debugging.\n\nExample output:\n\n\tContact system administrator with error details for investigation\n\n```go\nfunc ExampleWrap()\n```\nExampleWrap demonstrates wrapping errors with context.\n\nNote: Wrap annotates the original error with a new message and adds a stack trace. The original error is preserved in the error chain.\n\nExample output:\n\n\tfailed to connect to database\n\n```go\nfunc ExampleWrapC()\n```\nExampleWrapC demonstrates wrapping errors with code and namespace.\n\nNote: The output shows the error code's external message (Ext field), not the custom message passed to WrapC. The namespace is automatically injected.\n\nExample output:\n\n\tProvide a valid authentication token\n\n```go\nfunc ExampleWrapf()\n```\nExampleWrapf demonstrates wrapping errors with formatted message.\n\nNote: Wrapf annotates the original error with a formatted message and adds a stack trace. The original error is preserved in the error chain.\n\nExample output:\n\n\tfailed to write data to /var/log\n\n```go\nfunc FilterOut(err error, fns ...errors.Matcher) error\n```\nFilterOut removes all errors that match any of the matchers from the input error.\n\nExample:\n\n\tfiltered := FilterOut(agg, func(err error) bool {\n\t\treturn IsCode(err, ErrPageNotFound)\n\t})\n\tfmt.Println(filtered)\n\n```go\nfunc Flatten(agg errors.Aggregate) errors.Aggregate\n```\nFlatten takes an Aggregate and flattens them all into a single Aggregate, recursively.\n\nExample:\n\n\tflattened := Flatten(nestedAgg)\n\tfmt.Println(flattened)\n\n```go\nfunc Is(err, target error) bool\n```\nIs reports whether any error in err's chain matches target.\n\nExample:\n\n\tif Is(err, io.EOF) {\n\t\tfmt.Println(\"End of stream\")\n\t}\n\n```go\nfunc IsCode(err error, code int) bool\n```\nIsCode reports whether any error in err's chain contains the given error code within the specified namespace.\n\nExample:\n\n\tif IsCode(err, ErrPageNotFound) {\n\t\tfmt.Println(\"Page not found\")\n\t}\n\n```go\nfunc New(message string) error\n```\nNew returns an error with the supplied message. New also records the stack trace at the point it was called.\n\nExample:\n\n\terr := New(\"invalid email format\")\n\tfmt.Println(err)          // Output: invalid email format\n\tfmt.Printf(\"%+v\\n\", err) // Output: invalid email format - stack trace details\n\n```go\nfunc NewAggregate(errlist []error) errors.Aggregate\n```\nNewAggregate converts a slice of errors into an Aggregate interface.\n\nExample:\n\n\tagg := NewAggregate([]error{err1, err2})\n\tfmt.Println(agg)          // Output: [error1 message, error2 message]\n\tfmt.Printf(\"%+v\\n\", agg) // Output: [error1 details, error2 details]\n\n```go\nfunc Reduce(err error) error\n```\nReduce will return err or, if err is an Aggregate and only has one item, the first item.\n\nExample:\n\n\treduced := Reduce(agg)\n\tfmt.Println(reduced)\n\n```go\nfunc Unwrap(err error) error\n```\nUnwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.\n\nExample:\n\n\tunwrapped := Unwrap(wrappedErr)\n\tfmt.Println(unwrapped)\n\n```go\nfunc WithCode(code int, format string, args ...interface{}) error\n```\nWithCode creates an error with code and auto-injected namespace.\n\nExample:\n\n\terr := WithCode(ErrPageNotFound, \"user %s not found\", \"12345\")\n\tfmt.Println(err)          // Output: Check the URL path and try again\n\tfmt.Printf(\"%+v\\n\", err) // Output: user 12345 not found - #0 (codeexample:100006) Check the URL path and try again\n\n```go\nfunc WithMessage(err error, message string) error\n```\nWithMessage annotates err with a new message.\n\nExample:\n\n\terr := WithMessage(originalErr, \"failed to parse request body\")\n\tfmt.Println(err)          // Output: failed to parse request body\n\tfmt.Printf(\"%+v\\n\", err) // Output: failed to parse request body - stack trace details\n\n```go\nfunc WithMessagef(err error, format string, args ...interface{}) error\n```\nWithMessagef annotates err with a formatted message.\n\nExample:\n\n\terr := WithMessagef(originalErr, \"failed to encode %s response\", \"JSON\")\n\tfmt.Println(err)          // Output: failed to encode JSON response\n\tfmt.Printf(\"%+v\\n\", err) // Output: failed to encode JSON response - stack trace details\n\n```go\nfunc WithStack(err error) error\n```\nWithStack annotates err with a stack trace.\n\nExample:\n\n\terr := WithStack(originalErr)\n\tfmt.Println(err)          // Output: original error message\n\tfmt.Printf(\"%+v\\n\", err) // Output: original error message - stack trace details\n\n```go\nfunc Wrap(err error, message string) error\n```\nWrap returns an error annotating err with a stack trace at the point Wrap is called, and the supplied message.\n\nExample:\n\n\terr := Wrap(originalErr, \"failed to connect to database\")\n\tfmt.Println(err)          // Output: failed to connect to database\n\tfmt.Printf(\"%+v\\n\", err) // Output: failed to connect to database - stack trace details\n\n```go\nfunc WrapC(err error, code int, format string, args ...interface{}) error\n```\nWrapC wraps an error with code and auto-injected namespace.\n\nExample:\n\n\terr := WrapC(originalErr, ErrDatabase, \"failed to connect to %s\", \"db\")\n\tfmt.Println(err)          // Output: Contact system administrator to resolve database connectivity issue\n\tfmt.Printf(\"%+v\\n\", err) // Output: failed to connect to db - #0 (codeexample:100007) Contact system administrator to resolve database connectivity issue\n\n```go\nfunc Wrapf(err error, format string, args ...interface{}) error\n```\nWrapf returns an error annotating err with a stack trace at the point Wrapf is called, and the format specifier.\n\nExample:\n\n\terr := Wrapf(originalErr, \"failed to write to %s\", \"/var/log\")\n\tfmt.Println(err)          // Output: failed to write to /var/log\n\tfmt.Printf(\"%+v\\n\", err) // Output: failed to write to /var/log - stack trace details\n\n","path":"github.com/ClessLi/component-base/examples/code","name":"code","synopsis":"Package code demonstrates how to define error codes for a project.","isRedistributable":true}
