errors

package
v0.2.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2025 License: MIT Imports: 14 Imported by: 1

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

View Source
const (
	SupportPackageIsVersion1 = kerrors.SupportPackageIsVersion1
	UnknownCode              = kerrors.UnknownCode
	UnknownReason            = kerrors.UnknownReason
)

Variables

View Source
var (
	E_Code                   = kerrors.E_Code
	E_DefaultCode            = kerrors.E_DefaultCode
	File_errors_errors_proto = kerrors.File_errors_errors_proto
)

Functions

func As

func As(err error, target any) bool

func BadRequest

func BadRequest(reason, message string) *kerrors.Error

func ClientClosed

func ClientClosed(reason, message string) *kerrors.Error

func Clone

func Clone(err *kerrors.Error) *kerrors.Error

func Code

func Code(err error) int

func Conflict

func Conflict(reason, message string) *kerrors.Error

func Convert

func Convert(err error) *kerrors.Error

Convert takes any standard Go error and converts it into a structured Kratos error.

func Errorf

func Errorf(code int, reason, format string, a ...any) error

func Forbidden

func Forbidden(reason, message string) *kerrors.Error

func FromError

func FromError(err error) *kerrors.Error

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 GatewayTimeout(reason, message string) *kerrors.Error

func InternalServer

func InternalServer(reason, message string) *kerrors.Error

func Is

func Is(err, target error) bool

func IsBadRequest

func IsBadRequest(err error) bool

func IsClientClosed

func IsClientClosed(err error) bool

func IsConflict

func IsConflict(err error) bool

func IsForbidden

func IsForbidden(err error) bool

func IsGatewayTimeout

func IsGatewayTimeout(err error) bool

func IsInternalServer

func IsInternalServer(err error) bool

func IsNotFound

func IsNotFound(err error) bool

func IsServiceUnavailable

func IsServiceUnavailable(err error) bool

func IsUnauthorized

func IsUnauthorized(err error) bool

func LookupMeta

func LookupMeta(err error, key string) (string, bool)

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

func MethodNotAllowed(reason, message string) *kerrors.Error

MethodNotAllowed creates a 405 Method Not Allowed error.

func New

func New(code int, reason, message string) *kerrors.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 Newf

func Newf(code int, reason, format string, a ...any) *kerrors.Error

func NotFound

func NotFound(reason, message string) *kerrors.Error

func Reason

func Reason(err error) string

func RequestTimeout

func RequestTimeout(reason, message string) *kerrors.Error

RequestTimeout creates a 408 Request Timeout error.

func ServiceUnavailable

func ServiceUnavailable(reason, message string) *kerrors.Error

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

func TooManyRequests(reason, message string) *kerrors.Error

TooManyRequests creates a 429 Too Many Requests error.

func Unauthorized

func Unauthorized(reason, message string) *kerrors.Error

func Unwrap

func Unwrap(err error) error

func WithAudience

func WithAudience(err error, audience string) *kerrors.Error

WithAudience adds the 'audience' metadata to an error. Example: WithAudience(err, "user"), WithAudience(err, "developer"), WithAudience(err, "operator")

func WithBusinessDomain

func WithBusinessDomain(err error, domain string) *kerrors.Error

WithBusinessDomain adds the 'business_domain' metadata to an error. Example: WithBusinessDomain(err, "user_management"), WithBusinessDomain(err, "order_processing")

func WithErrorOrigin

func WithErrorOrigin(err error, origin string) *kerrors.Error

WithErrorOrigin adds the 'error_origin' metadata to an error. Example: WithErrorOrigin(err, "database"), WithErrorOrigin(err, "network")

func WithField

func WithField(err error, key string, value interface{}) *kerrors.Error

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

func WithImpact(err error, impact string) *kerrors.Error

WithImpact adds the 'impact' metadata to an error. Example: WithImpact(err, "fatal"), WithImpact(err, "critical"), WithImpact(err, "minor")

func WithMessage

func WithMessage(err error, format string, args ...interface{}) *kerrors.Error

WithMessage enhances an error with a more specific message. It converts the error to a Kratos error first, then sets the message.

func WithMeta

func WithMeta(err error, meta map[string]interface{}) *kerrors.Error

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

func WithRecoverability(err error, status string) *kerrors.Error

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 Error

type Error = kerrors.Error

type Status

type Status = kerrors.Status

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) Error

func (e *Structured) Error() string

Error returns the error message

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) Unwrap

func (e *Structured) Unwrap() error

Unwrap returns the underlying error

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL