Documentation
¶
Overview ¶
Package errors provides enhanced error handling with module support, error codes, and metadata.
This package extends the standard error handling with additional features and is divided into two main parts:
1. API interface unified error handling (integration with Kratos errors) 2. Internal module error creation and handling
The package also provides utilities for working with error metadata and compatibility with the standard errors package.
Basic Usage:
// Create a new structured error for internal module use
err := errors.New("auth", "INVALID_TOKEN", "invalid authentication token")
// Add operation context
err = err.WithCaller() // Automatically gets the caller function name
// or
err = err.WithOperation("CheckToken") // Manually set operation name
// Add metadata
err = err.WithField("user_id", 123)
// Wrap an existing error
err = errors.Wrap(err, "db", "QUERY_FAILED", "failed to query user")
// Convert to Kratos error for API responses
kratosErr := errors.ToKratos(err, commonv1.ErrorReason_UNAUTHENTICATED)
// Check error type
if errors.Is(err, &errors.Structured{Module: "auth", Code: "INVALID_TOKEN"}) {
// Handle invalid token
}
// Working with error metadata
if val, ok := errors.LookupMeta(kratosErr, "user_id"); ok {
// Use the metadata
}
Package errors provides a centralized hub for handling, converting, and rendering errors. It uses a proto-defined enum for standard error reasons and adapts the Kratos error package.
Package errors contains generated code by adptool.
Package errors provides a centralized hub for handling, converting, and rendering errors. It provides custom error handlers/encoders for HTTP and gRPC that integrate with the Kratos ecosystem while providing centralized logging and error conversion.
Package errors provides a centralized hub for handling, converting, and rendering errors.
Index ¶
- Constants
- Variables
- func As(err error, target any) bool
- func BadRequest(reason, message string) *kerrors.Error
- func ClientClosed(reason, message string) *kerrors.Error
- func Clone(err *kerrors.Error) *kerrors.Error
- func Code(err error) int
- func Conflict(reason, message string) *kerrors.Error
- func Convert(err error) *kerrors.Error
- func Errorf(code int, reason, format string, a ...any) error
- func Forbidden(reason, message string) *kerrors.Error
- func FromError(err error) *kerrors.Error
- func FromReason(reason commonv1.ErrorReason) *kerrors.Error
- func GatewayTimeout(reason, message string) *kerrors.Error
- func InternalServer(reason, message string) *kerrors.Error
- func Is(err, target error) bool
- func IsBadRequest(err error) bool
- func IsClientClosed(err error) bool
- func IsConflict(err error) bool
- func IsForbidden(err error) bool
- func IsGatewayTimeout(err error) bool
- func IsInternalServer(err error) bool
- func IsNotFound(err error) bool
- func IsServiceUnavailable(err error) bool
- func IsUnauthorized(err error) bool
- func LookupMeta(err error, key string) (string, bool)
- func MethodNotAllowed(reason, message string) *kerrors.Error
- func New(code int, reason, message string) *kerrors.Error
- func NewErrorEncoder() transhttp.EncodeErrorFunc
- func NewMessage(reason commonv1.ErrorReason, format string, a ...interface{}) *kerrors.Error
- func NewMessageWithMeta(reason commonv1.ErrorReason, metadata map[string]string, format string, ...) *kerrors.Error
- func Newf(code int, reason, format string, a ...any) *kerrors.Error
- func NotFound(reason, message string) *kerrors.Error
- func Reason(err error) string
- func RequestTimeout(reason, message string) *kerrors.Error
- func ServiceUnavailable(reason, message string) *kerrors.Error
- func ToKratos(e *Structured, reason commonv1.ErrorReason) *kerrors.Error
- func TooManyRequests(reason, message string) *kerrors.Error
- func Unauthorized(reason, message string) *kerrors.Error
- func Unwrap(err error) error
- func WithAudience(err error, audience string) *kerrors.Error
- func WithBusinessDomain(err error, domain string) *kerrors.Error
- func WithErrorOrigin(err error, origin string) *kerrors.Error
- func WithField(err error, key string, value interface{}) *kerrors.Error
- func WithImpact(err error, impact string) *kerrors.Error
- func WithMessage(err error, format string, args ...interface{}) *kerrors.Error
- func WithMeta(err error, meta map[string]interface{}) *kerrors.Error
- func WithReason(err error, reason commonv1.ErrorReason) error
- func WithRecoverability(err error, status string) *kerrors.Error
- func WrapAndConvert(originalErr error, reason commonv1.ErrorReason, format string, ...) *kerrors.Error
- type Error
- type Status
- type Structured
- func (e *Structured) Error() string
- func (e *Structured) Is(target error) bool
- func (e *Structured) Unwrap() error
- func (e *Structured) WithCaller() *Structured
- func (e *Structured) WithField(key string, value string) *Structured
- func (e *Structured) WithMetadata(metadata map[string]string) *Structured
- func (e *Structured) WithOperation(op string) *Structured
- func (e *Structured) Wrap(err error) *Structured
- type TaggedError
Constants ¶
const ( SupportPackageIsVersion1 = kerrors.SupportPackageIsVersion1 UnknownCode = kerrors.UnknownCode UnknownReason = kerrors.UnknownReason )
Variables ¶
var ( E_Code = kerrors.E_Code E_DefaultCode = kerrors.E_DefaultCode File_errors_errors_proto = kerrors.File_errors_errors_proto )
Functions ¶
func BadRequest ¶
func ClientClosed ¶
func FromReason ¶
func FromReason(reason commonv1.ErrorReason) *kerrors.Error
FromReason creates a Kratos error from a predefined error reason from the .proto file. This is the primary and consistent way to create standard application errors.
func GatewayTimeout ¶
func InternalServer ¶
func IsBadRequest ¶
func IsClientClosed ¶
func IsConflict ¶
func IsForbidden ¶
func IsGatewayTimeout ¶
func IsInternalServer ¶
func IsNotFound ¶
func IsServiceUnavailable ¶
func IsUnauthorized ¶
func LookupMeta ¶
LookupMeta retrieves a specific metadata value from a Kratos error. It returns the value and a boolean indicating if the key was found.
func MethodNotAllowed ¶
MethodNotAllowed creates a 405 Method Not Allowed error.
func NewErrorEncoder ¶
func NewErrorEncoder() transhttp.EncodeErrorFunc
NewErrorEncoder returns a new transhttp.EncodeErrorFunc for centralized logging and error conversion.
func NewMessage ¶
func NewMessage(reason commonv1.ErrorReason, format string, a ...interface{}) *kerrors.Error
NewMessage creates a Kratos error from a predefined error reason, with a formatted message.
func NewMessageWithMeta ¶
func NewMessageWithMeta(reason commonv1.ErrorReason, metadata map[string]string, format string, a ...interface{}) *kerrors.Error
NewMessageWithMeta creates a Kratos error from a predefined error reason, with a formatted message and specified metadata.
func RequestTimeout ¶
RequestTimeout creates a 408 Request Timeout error.
func ServiceUnavailable ¶
func ToKratos ¶
func ToKratos(e *Structured, reason commonv1.ErrorReason) *kerrors.Error
ToKratos converts an internal Structured error to a Kratos error for API responses. This function resides in a dedicated API adapter to keep internal errors decoupled from API logic.
func TooManyRequests ¶
TooManyRequests creates a 429 Too Many Requests error.
func Unauthorized ¶
func WithAudience ¶
WithAudience adds the 'audience' metadata to an error. Example: WithAudience(err, "user"), WithAudience(err, "developer"), WithAudience(err, "operator")
func WithBusinessDomain ¶
WithBusinessDomain adds the 'business_domain' metadata to an error. Example: WithBusinessDomain(err, "user_management"), WithBusinessDomain(err, "order_processing")
func WithErrorOrigin ¶
WithErrorOrigin adds the 'error_origin' metadata to an error. Example: WithErrorOrigin(err, "database"), WithErrorOrigin(err, "network")
func WithField ¶
WithField adds a single key-value pair as metadata to an error. It converts the error to a Kratos error first, then adds the field.
func WithImpact ¶
WithImpact adds the 'impact' metadata to an error. Example: WithImpact(err, "fatal"), WithImpact(err, "critical"), WithImpact(err, "minor")
func WithMessage ¶
WithMessage enhances an error with a more specific message. It converts the error to a Kratos error first, then sets the message.
func WithMeta ¶
WithMeta adds structured metadata to an error. It converts the error to a Kratos error first, then adds the metadata.
func WithReason ¶
func WithReason(err error, reason commonv1.ErrorReason) error
WithReason tags a generic error with a specific ErrorReason. This allows Convert to map it to a specific Kratos error type.
func WithRecoverability ¶
WithRecoverability adds the 'recoverability' metadata to an error. Example: WithRecoverability(err, "retriable"), WithRecoverability(err, "non_retriable")
func WrapAndConvert ¶
func WrapAndConvert(originalErr error, reason commonv1.ErrorReason, format string, a ...interface{}) *kerrors.Error
WrapAndConvert wraps an original error with a reason, converts it to a Kratos error, and sets a formatted message.
Types ¶
type Structured ¶
type Structured struct {
// Module indicates which module the error occurred in (e.g., "auth", "db")
Module string `json:"module"`
// Message is the human-readable error message
Message string `json:"message"`
// Op is the operation that caused the error (usually the function name)
Op string `json:"operation,omitempty"`
// Metadata contains additional context about the error
Metadata map[string]string `json:"metadata,omitempty"`
// Err is the underlying error
Err error `json:"-"`
}
Structured represents an error with module context and structured metadata. This type is primarily used for internal module error handling.
func NewStructured ¶
func NewStructured(module, format string, args ...interface{}) *Structured
NewStructured creates a new structured error
func WrapStructured ¶
func WrapStructured(err error, module, format string, args ...interface{}) *Structured
WrapStructured wraps an error with additional context
func (*Structured) Is ¶
func (e *Structured) Is(target error) bool
Is checks if the target error is of type *Structured and matches based on module
func (*Structured) WithCaller ¶
func (e *Structured) WithCaller() *Structured
WithCaller adds operation context to the error by getting the caller function name
func (*Structured) WithField ¶
func (e *Structured) WithField(key string, value string) *Structured
WithField adds a single key-value pair to the error metadata
func (*Structured) WithMetadata ¶
func (e *Structured) WithMetadata(metadata map[string]string) *Structured
WithMetadata adds metadata to the error
func (*Structured) WithOperation ¶
func (e *Structured) WithOperation(op string) *Structured
WithOperation sets a specific operation name for the error
func (*Structured) Wrap ¶ added in v0.2.11
func (e *Structured) Wrap(err error) *Structured
type TaggedError ¶
type TaggedError struct {
Err error
Reason commonv1.ErrorReason
}
TaggedError is an error that carries a specific ErrorReason. This allows for explicit mapping of generic errors to predefined reasons.
func (*TaggedError) Error ¶
func (e *TaggedError) Error() string
func (*TaggedError) Unwrap ¶
func (e *TaggedError) Unwrap() error