erro

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 18 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ΒΆ

πŸš€ erro - Next-Generation Error Handling for Go

Go Version GoDoc Build Coverage GoReport

Move your error handling to the next level. erro is a powerful, production-ready error library that gives you everything the standard errors package should have provided: structured context, stack traces, automatic HTTP status codes, seamless logging integration and comprehensive debugging tools.

πŸ“¦ Installation
go get -u github.com/maxbolgarin/erro

✨ Why erro > standard errors?

Before: Basic Go errors leave you guessing

// Standard Go - minimal context, hard to debug
return fmt.Errorf("user operation failed: %w", err)

// What went wrong? Which user? What operation? What's the HTTP status?
// You'll spend time digging through logs to find out.

After: Rich, actionable errors with full context

// erro - rich context, automatic status codes, structured logging
return erro.Wrap(err, "failed to update user profile",
    "user_id", userID,
    "operation", "profile_update", 
    erro.ClassValidation,        // β†’ HTTP 400
    erro.CategoryUserInput,      // β†’ Organized error tracking
    erro.SeverityMedium,         // β†’ Priority for alerts
    erro.RecordSpan(span),       // β†’ OpenTelemetry tracing
    erro.RecordMetrics(metrics), // β†’ Prometheus metrics
    erro.SendEvent(ctx, dispatcher),  // β†’ Error event tracking (e.g. Sentry, Honeycomb, etc.)
)

// Instant context: exactly what failed, for whom, why, and how to respond

🎯 Key Benefits

  • πŸ” Rich Context: Error carries structured metadata, stack traces, and debugging information with smart classification
  • πŸ“Š Logging-Native: Integration with slog, logrus and any structured logger
  • πŸ” Monitoring-Native: Easyly gather metrics, trace spans or send events on error creation
  • πŸ”’ Security-Aware: Redaction of sensitive data in logs and traces, protection from DoS attacks
  • πŸ”„ Drop-in Replacement: Fully compatible with standard errors package - migrate gradually or just replace errors to erro in your codebase
  • 🎯 Production-Ready: Comprehensive testing, thread-safe, used in production environments, performance is suitable for 95% of use cases (watch benchmarks below)

πŸš€ Quick Start

package main

import (
    "encoding/json"
    "log/slog"
    "net/http"

    "github.com/maxbolgarin/erro"
)

// Create rich errors with context
func GetUser(id int) (*User, error) {
    user, err := db.FindUser(id)
    if err != nil {
        return nil, erro.Wrap(err, "failed to retrieve user",
            "user_id", id,
            "table", "users",
            erro.ClassNotFound,      // β†’ HTTP 404
            erro.CategoryDatabase,   // β†’ Error grouping
        )
    }
    return user, nil
}

// HTTP handler with automatic status codes
func UserHandler(w http.ResponseWriter, r *http.Request) {
    user, err := GetUser(123)
    if err != nil {
        // Automatic HTTP status code mapping
        statusCode := erro.HTTPCode(err)  // 404 from ClassNotFound
        
        // Rich structured logging
        slog.Error("user retrieval failed", erro.LogFields(err)...)
        
        http.Error(w, err.Error(), statusCode)
        return
    }
    
    json.NewEncoder(w).Encode(user)
}

πŸ”₯ Advanced Features

🏷️ Error Templates - Consistency Made Easy

Tutorial: Error Templates

// Define reusable error templates
var (
    ValidationError = erro.NewTemplate("validation failed: %s",
        erro.ClassValidation,
        erro.CategoryUserInput,
        erro.SeverityLow,
    )
)

// Use templates for consistent error creation
func ValidateEmail(email string) error {
    if !isValidEmail(email) {
        return ValidationError.New("invalid email format", 
            "email", email,
            "pattern", emailRegex,
        )
    }
    return nil
}
πŸ“Š Error Collections - Handle Multiple Errors
// Collect multiple validation errors
validator := erro.NewList()
validator.New("email required", "field", "email", erro.ClassValidation)
validator.New("password too short", "field", "password", "min_length", 8)

// Return all errors at once
if err := validator.Err(); err != nil {
    return err  // "multiple errors (2): [1] email required; [2] password too short"
}

// Thread-safe collections for concurrent operations
safeCollector := erro.NewSafeSet()  // Deduplicates identical errors
πŸ”’ Security & Sensitive Data Protection
func AuthenticateUser(username, password string) error {
    err := bcrypt.CompareHashAndPassword(hashedPassword, []byte(password))
    if err != nil {
        return erro.Wrap(err, "authentication failed",
            "username", username,
            "password", erro.Redact(password),  // Automatically redacted in logs
            "ip_address", clientIP,
            "attempt_count", attemptCount,
            erro.ClassUnauthenticated,
        )
    }
    return nil
}
πŸ” Stack Traces & Debugging

Tutorial: Stack Trace Configuration

// Capture stack traces for debugging
func CriticalOperation() error {
    return erro.New("critical system failure",
        "component", "payment_processor",
        "transaction_id", txID,
        erro.StackTrace(),           // Capture stack trace
        erro.ClassCritical,
        erro.SeverityCritical,
    )
}

// Print detailed stack trace
fmt.Printf("%+v\n", err)  // Full stack trace with file:line info
🌐 HTTP Integration & REST APIs
// Automatic HTTP status code mapping
func APIErrorHandler(err error) (int, any) {
    statusCode := erro.HTTPCode(err)  // Intelligent mapping
    
    response := map[string]any{
        "error": err.Error(),
        "status": statusCode,
        "timestamp": time.Now(),
    }
    
    // Add structured error details
    if erroErr, ok := err.(erro.Error); ok {
        response["error_id"] = erroErr.ID()      // Unique error ID
        response["class"] = erroErr.Class()      // Error classification
        response["severity"] = erroErr.Severity() // Priority level
        response["retryable"] = erroErr.IsRetryable()
        response["fields"] = erroErr.LogFieldsMap()
    }
    
    return statusCode, response
}

// Status code mapping examples:
// erro.ClassValidation      β†’ 400 Bad Request
// erro.ClassNotFound        β†’ 404 Not Found  
// erro.ClassUnauthenticated β†’ 401 Unauthorized
// erro.ClassPermissionDenied β†’ 403 Forbidden
// erro.ClassRateLimited     β†’ 429 Too Many Requests
// erro.ClassExternal        β†’ 502 Bad Gateway
πŸ“ˆ Observability & Monitoring Integration
// Integrate with tracing, metrics, and events
func ProcessPayment(ctx context.Context, amount float64) error {
    // ...
    
    return erro.New("payment processing failed",
        "amount", amount,
        "currency", "USD",
        "merchant_id", merchantID,
        
        // Observability integrations
        erro.RecordSpan(span),              // OpenTelemetry tracing
        erro.RecordMetrics(metricsCollector), // Prometheus metrics
        erro.SendEvent(ctx, eventDispatcher), // Error event tracking
        
        erro.ClassExternal,
        erro.CategoryPayment,
        erro.SeverityCritical,
    )
}

πŸ”„ Migration Guide

Drop-in Replacement
// Before: Standard errors
import "errors"

err := errors.New("something failed")
// After: Rich errors
import "github.com/maxbolgarin/erro"

err := erro.New("something failed")

// All standard functions still work
if erro.Is(err, err1) { ... }  // βœ… Works
erro.Unwrap(err1)  // βœ… Works
Gradual Enhancement
// Phase 1: Basic replacement
- return errors.New("user not found")
+ return erro.New("user not found")

// Phase 2: Add context  
+ return erro.New("user not found", "user_id", id)

// Phase 3: Add classification
+ return erro.New("user not found", "user_id", id, erro.ClassNotFound)

// Phase 4: Full features
+ return erro.New("user not found",
+     "user_id", id,
+     "table", "users", 
+     erro.ClassNotFound,
+     erro.CategoryDatabase,
+ )

πŸ“Š Performance & Benchmark

What AI says about this package after writing edge cases tests

The erro library now demonstrates:

  • Robust security with DoS protection
  • Excellent performance (~416ns/error)
  • Memory safety with no leaks
  • Thread safety with comprehensive concurrency testing
  • Standards compliance with Go error interfaces
  • High test coverage with extensive edge case coverage
Benchmarks
go test -bench . -benchmem
goos: darwin
goarch: arm64
pkg: github.com/maxbolgarin/erro
cpu: Apple M1 Pro
New
Benchmark_New_STD-8                                   1000000000               0.317 ns/op           0 B/op            0 allocs/op

Benchmark_New-8                                         12095107               103.7 ns/op           304 B/op          2 allocs/op
Benchmark_New_WithFields-8                               6548682               188.3 ns/op           432 B/op          3 allocs/op
Benchmark_New_WithFieldsAndFormatVerbs-8                 4174512               291.4 ns/op           496 B/op          4 allocs/op
Benchmark_NewWithStack-8                                 1848162               638.7 ns/op           400 B/op          4 allocs/op
Benchmark_NewWithStack_WithFields-8                      1523343               798.2 ns/op           528 B/op          5 allocs/op
Wrap
Benchmark_Errorf_STD-8                                  13115816               92.91 ns/op            80 B/op          2 allocs/op
Benchmark_Errorf_STD_WithFields-8                        3420916               351.6 ns/op           128 B/op          2 allocs/op

Benchmark_Wrap_STD-8                                     5994091               198.8 ns/op           304 B/op          2 allocs/op
Benchmark_Wrap_WithFields-8                              4139568               285.9 ns/op           432 B/op          3 allocs/op
Benchmark_Wrap_WithFieldsAndFormatVerbs-8                3017126               382.7 ns/op           496 B/op          4 allocs/op
Benchmark_WrapWithStack-8                                1405453               865.5 ns/op           400 B/op          4 allocs/op
Benchmark_WrapWithStack_WithFields-8                     1374007               833.5 ns/op           528 B/op          5 allocs/op
Benchmark_Wrap_Erro_NoIDGeneration-8                    21970459               55.82 ns/op           288 B/op          1 allocs/op
Error() - has cache, only first call is slow
Benchmark_New_ErrorString-8                             456379255                2.618 ns/op           0 B/op          0 allocs/op
Benchmark_New_ErrorString_WithFields-8                  461110897                3.705 ns/op           0 B/op          0 allocs/op
Benchmark_Wrap_Error_Deep-8                             433859401                2.739 ns/op           0 B/op          0 allocs/op
AllMeta - optimized means preallocation slice of options
Benchmark_New_AllMeta_WithStack-8                        1000000               1099 ns/op            968 B/op         14 allocs/op
Benchmark_New_AllMeta_NoStack-8                          2327088               529.9 ns/op           864 B/op         11 allocs/op
Benchmark_New_AllMeta_NoStack_Optimized-8                5052752               237.5 ns/op           416 B/op          2 allocs/op
LogFields
Benchmark_Error_Context-8                               33381976               35.83 ns/op           64 B/op           1 allocs/op
Benchmark_LogFields_Default-8                            3711354               323.6 ns/op           784 B/op         11 allocs/op
Benchmark_LogFields_Minimal-8                            4714416               271.2 ns/op           736 B/op          6 allocs/op
Benchmark_LogFields_Verbose-8                            3029905               402.6 ns/op           856 B/op         13 allocs/op
Benchmark_LogFieldsMap-8                                 2212669               544.1 ns/op          1448 B/op         15 allocs/op
Benchmark_LogError-8                                     3457154               343.5 ns/op           800 B/op         12 allocs/op
Template
Benchmark_New_Template-8                                 5231294               252.5 ns/op           448 B/op         10 allocs/op
Benchmark_New_FromTemplate-8                             5056893               225.0 ns/op           432 B/op          2 allocs/op
Benchmark_New_FromTemplate_WithMessageAndFields-8        3497571               361.6 ns/op           608 B/op          4 allocs/op
Benchmark_New_FromTemplate_Full-8                        1249724               1097 ns/op            672 B/op          5 allocs/op
Benchmark_Wrap_FromTemplate-8                            5267229               195.9 ns/op           432 B/op          2 allocs/op
Benchmark_Wrap_FromTemplate_WithMessageAndFields-8       3900334               311.4 ns/op           608 B/op          4 allocs/op
Benchmark_Wrap_FromTemplate_Full-8                       1364061               899.7 ns/op           672 B/op          5 allocs/op
HTTPCode
Benchmark_HTTPCode_Class-8                              59561968                20.13 ns/op           16 B/op          1 allocs/op
Benchmark_HTTPCode_Category-8                           59894061                20.23 ns/op           16 B/op          1 allocs/op
Sprintf vs ApplyFormatVerbs
Benchmark_Sprintf-8                                      3375201               353.9 ns/op           144 B/op          5 allocs/op
Benchmark_ApplyFormatVerbs-8                             2938574               410.8 ns/op           160 B/op          5 allocs/op

ApplyFormatVerbs does full fmt-compatible verb parsing (flags, width, precision) plus value truncation, redaction of erro.Redact values, and skipping of erro options β€” that safety costs a bit on numeric-verb-heavy formats. For the common %s/%v-only messages it stays faster than fmt.Sprintf, and unused arguments become structured fields instead of %!(EXTRA ...) noise.

🎯 Performance Insights

⚑ Operations Insights

  • Standard errors.New(): 0.32ns (baseline, no features)
  • erro.New() no fields: 104ns (small overhead in most cases)
  • Standard fmt.Errorf() with only error wrapped: 93ns
  • Standard fmt.Errorf() with error wrapped and many fields: 352ns
  • erro.Wrap() no fields with errors.New wrapping: 199ns (overhead like erro.New + wrapping logic)
  • erro.Wrap() with fields: 286ns (faster than fmt.Errorf() with fields)
  • erro.Wrap() is fast (56ns) if you already have an erro.Error, so in long chains it wins over many fmt.Errorf()
  • Cached Error() string: ~2.6ns after the first call
  • HTTP status code mapping: 20ns - virtually zero overhead

πŸ€” Consider Alternatives For

  • Ultra-high Performance - If you need absolute minimal overhead (so do not use fmt.Errorf and fmt.Sprintf)
  • Simple Scripts - Standard errors might be sufficient for basic scripts
  • Legacy Codebases - If you can't gradually migrate existing error handling

Why Go's approach to errors is better than exceptions?

Go's approach to errorsβ€”as values rather than exceptionsβ€”offers significant advantages for modern microservice and observability-driven architectures.

By treating errors as explicit return values, Go encourages developers to handle failures directly at the point where they occur, making error flows transparent and predictable. This explicitness enables rich error wrapping, structured context, and metadata propagation, which are essential for tracing issues across distributed systems. Unlike try-catch mechanisms that can obscure the origin and context of failures, Go's model makes it easy to:

  • attach contextual information
  • correlate errors with logs and traces
  • surface actionable insights for monitoring and debugging

As a result, error handling in Go aligns naturally with the needs of production-grade systems, where observability, debuggability, and reliability are paramount. Use the natural strength of Go approach to errors and build your systems with observability in mind.

πŸ“š Documentation

🀝 Contributing

We welcome contributions! Open an issue or submit a pull request.

πŸ“„ License

MIT License - see LICENSE for details.

Documentation ΒΆ

Overview ΒΆ

Package erro provides a comprehensive error handling library for Go, offering features like error wrapping, structured logging, stack traces, and error classification. It is designed to be a drop-in replacement for the standard `errors` package, providing more context and control over error handling.

Index ΒΆ

Constants ΒΆ

View Source
const (
	// MaxMessageLength is the maximum length for error messages.
	MaxMessageLength = 1000
	// MaxKeyLength is the maximum length for field keys.
	MaxKeyLength = 128
	// MaxValueLength is the maximum length for field values when converted to a string.
	MaxValueLength = 1024

	// MaxFieldsCount is the maximum number of fields (key-value pairs).
	MaxFieldsCount = 100

	// MaxWrapDepth is the maximum depth of error wrapping.
	MaxWrapDepth = 50

	// MaxStackDepth is the maximum stack depth.
	MaxStackDepth = 50

	// RedactedPlaceholder is the placeholder for redacted values.
	RedactedPlaceholder = "[REDACTED]"
	// MissingFieldPlaceholder is the placeholder for missing field values.
	MissingFieldPlaceholder = "<missing>"
)

Security configuration constants

Variables ΒΆ

View Source
var (
	// DefaultLogOptions includes a balanced set of fields for typical logging.
	DefaultLogOptions = LogOptions{
		IncludeErrorMessage: true,
		IncludeUserFields:   true,
		IncludeID:           false,
		IncludeCategory:     true,
		IncludeSeverity:     true,
		IncludeTracing:      true,
		IncludeCreatedTime:  false,
		IncludeRetryable:    true,
		IncludeFunction:     true,
		IncludePackage:      false,
		IncludeFile:         false,
		IncludeLine:         false,
		IncludeStack:        false,
		StackFormat:         StackFormatJSON,
		FieldNamePrefix:     "error_",
	}

	// VerboseLogOpts is a slice of [LogOption] functions for verbose logging.
	VerboseLogOpts = []LogOption{
		WithErrorMessage(true),
		WithUserFields(true),
		WithID(true),
		WithSeverity(true),
		WithCategory(true),
		WithTracing(true),
		WithRetryable(true),
		WithCreatedTime(true),
		WithFunction(true),
		WithPackage(true),
		WithFile(true),
		WithLine(true),
		WithStack(true),
	}

	// MinimalLogOpts is a slice of [LogOption] functions for minimal logging.
	MinimalLogOpts = []LogOption{
		WithErrorMessage(true),
		WithUserFields(true),
		WithSeverity(true),
	}
)
View Source
var (
	// ValidationError creates a new validation error.
	ValidationError = NewTemplate("failed validation: %s",
		ClassValidation,
		CategoryUserInput,
		SeverityLow,
	)

	// NotFoundError creates a new not found error.
	NotFoundError = NewTemplate("%s not found",
		ClassNotFound,
		SeverityMedium,
	)

	// DatabaseError creates a new database error.
	DatabaseError = NewTemplate("database error: %s",
		CategoryDatabase,
		SeverityHigh,
	)

	// NetworkError creates a new network error.
	NetworkError = NewTemplate("network error: %s",
		CategoryNetwork,
		SeverityMedium,
		Retryable(),
	)

	// AuthenticationError creates a new authentication error.
	AuthenticationError = NewTemplate("authentication failed: %s",
		CategoryAuth,
		ClassUnauthenticated,
		SeverityMedium,
	)

	// AuthorizationError creates a new authorization error.
	AuthorizationError = NewTemplate("permission denied: %s",
		CategoryAuth,
		ClassPermissionDenied,
		SeverityHigh,
	)

	// TimeoutError creates a new timeout error.
	TimeoutError = NewTemplate("operation timeout: %s",
		ClassTimeout,
		SeverityLow,
		Retryable(),
	)

	// ConflictError creates a new conflict error.
	ConflictError = NewTemplate("conflict: %s",
		ClassConflict,
		SeverityMedium,
	)

	// RateLimitError creates a new rate limit error.
	RateLimitError = NewTemplate("rate limit exceeded: %s",
		ClassRateLimited,
		SeverityLow,
		Retryable(),
	)

	// InternalError creates a new internal error.
	InternalError = NewTemplate("internal error: %s",
		ClassInternal,
		SeverityHigh,
	)

	// SecurityError creates a new security error.
	SecurityError = NewTemplate("security violation: %s",
		ClassSecurity,
		CategorySecurity,
		SeverityCritical,
	)

	// ExternalError creates a new external service error.
	ExternalError = NewTemplate("external error: %s",
		ClassExternal,
		CategoryExternal,
		SeverityMedium,
		Retryable(),
	)

	// PaymentError creates a new payment error.
	PaymentError = NewTemplate("payment error: %s",
		CategoryPayment,
		SeverityCritical,
		Retryable(),
	)

	// CacheError creates a new cache error.
	CacheError = NewTemplate("cache error: %s",
		CategoryCache,
		ClassTemporary,
		SeverityMedium,
		Retryable(),
	)

	// ConfigError creates a new configuration error.
	ConfigError = NewTemplate("configuration error: %s",
		CategoryConfig,
		ClassInternal,
		SeverityCritical,
	)

	// APIError creates a new API error.
	APIError = NewTemplate("API error: %s",
		CategoryAPI,
		SeverityHigh,
	)

	// BusinessLogicError creates a new business logic error.
	BusinessLogicError = NewTemplate("business logic error: %s",
		CategoryBusinessLogic,
		SeverityHigh,
	)

	// StorageError creates a new storage error.
	StorageError = NewTemplate("storage error: %s",
		CategoryStorage,
		SeverityHigh,
	)

	// ProcessingError creates a new processing error.
	ProcessingError = NewTemplate("processing error: %s",
		CategoryProcessing,
		ClassInternal,
		SeverityHigh,
	)

	// MonitoringError creates a new monitoring error.
	MonitoringError = NewTemplate("monitoring error: %s",
		CategoryMonitoring,
		SeverityMedium,
	)

	// NotificationError creates a new notification error.
	NotificationError = NewTemplate("notification error: %s",
		CategoryNotifications,
		ClassTemporary,
		SeverityLow,
	)

	// AIError creates a new AI/ML error.
	AIError = NewTemplate("AI error: %s",
		CategoryAI,
		ClassInternal,
		SeverityHigh,
	)

	// AnalyticsError creates a new analytics error.
	AnalyticsError = NewTemplate("analytics error: %s",
		CategoryAnalytics,
		SeverityLow,
	)

	// EventsTemplate creates a new events error.
	EventsTemplate = NewTemplate("events error: %s",
		CategoryEvents,
		SeverityMedium,
	)

	// CriticalError creates a new critical error.
	CriticalError = NewTemplate("critical error: %s",
		ClassCritical,
		SeverityCritical,
	)

	// TemporaryError creates a new temporary error.
	TemporaryError = NewTemplate("temporary error: %s",
		ClassTemporary,
		SeverityMedium,
	)

	// DataLossError creates a new data loss error.
	DataLossError = NewTemplate("data loss: %s",
		ClassDataLoss,
		SeverityCritical,
	)

	// ResourceExhaustedError creates a new resource exhausted error.
	ResourceExhaustedError = NewTemplate("resource exhausted: %s",
		ClassResourceExhausted,
		SeverityHigh,
	)

	// UnavailableError creates a new unavailable error.
	UnavailableError = NewTemplate("service unavailable: %s",
		ClassUnavailable,
		SeverityHigh,
	)

	// CancelledError creates a new cancelled error.
	CancelledError = NewTemplate("operation cancelled: %s",
		ClassCancelled,
		SeverityLow,
	)

	// NotImplementedError creates a new not implemented error.
	NotImplementedError = NewTemplate("not implemented: %s",
		ClassNotImplemented,
		SeverityMedium,
	)

	// AlreadyExistsError creates a new already exists error.
	AlreadyExistsError = NewTemplate("already exists: %s",
		ClassAlreadyExists,
		SeverityMedium,
	)
)

Predefined error templates.

View Source
var (
	// ErrMaxWrapDepthExceeded is a sentinel reserved for wrap-depth overflow.
	//
	// Deprecated: it is no longer returned. When the wrap depth reaches
	// [MaxWrapDepth], [Wrap] returns the inner error unchanged instead of
	// adding another layer. Kept exported for API compatibility.
	ErrMaxWrapDepthExceeded = New("maximum wrap depth exceeded")
)

Functions ΒΆ

func ApplyFormatVerbs ΒΆ

func ApplyFormatVerbs(format string, args ...any) (result string, rest []any)

ApplyFormatVerbs replaces format verbs in a string with arguments.

It supports a subset of package fmt syntax: optional flags '+', '-', '#', '0', an optional width and precision (each up to 4 digits), and the verbs b c d e E f F g G o O p q s t T U v x X w ('%w' is formatted like '%v'). '%%' emits a literal '%'. Anything else β€” the space flag, '*' width, argument indexes like '%[1]d', unknown verbs β€” is emitted literally and consumes no argument, so messages like "90% done" stay intact. Once arguments run out, remaining verbs are emitted literally. Unconsumed arguments are returned for use as key-value fields.

func As ΒΆ

func As(err error, target any) (ok bool)

As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true. It is a drop-in replacement for the standard `errors.As` function.

func Close ΒΆ

func Close(err *error, cl io.Closer, msg string, fields ...any)

Close is a utility function that closes an io.Closer and wraps any resulting error. It is intended to be used in defer statements.

If the closer is nil, it does nothing. If the close operation returns an error, it will be wrapped with the provided message and fields.

Example:

func ReadData(path string) (data []byte, err error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, erro.Wrap(err, "failed to open file")
    }
    defer erro.Close(&err, f, "failed to close file")

    // ... read data from f
}

func Fields ΒΆ

func Fields(fields ...any) errorFields

Fields adds structured data to the error.

func FormatErrorMessage ΒΆ

func FormatErrorMessage(err Error) string

FormatErrorMessage formats an error with its message only.

func FormatErrorWithFields ΒΆ

func FormatErrorWithFields(err Error) string

FormatErrorWithFields formats an Error with its message and fields.

func Formatter ΒΆ

func Formatter(f FormatErrorFunc) errorOpt

Formatter sets a custom error message formatter.

func HTTPCode ΒΆ

func HTTPCode(err error) int

HTTPCode returns an appropriate HTTP status code for a given error.

This function provides automatic HTTP status code mapping based on error classification, enabling seamless integration between your application's error handling and HTTP responses.

Error Class Mappings ΒΆ

The following error classes map to specific HTTP status codes:

ClassValidation        -> 400 Bad Request
ClassNotFound          -> 404 Not Found
ClassAlreadyExists     -> 409 Conflict
ClassPermissionDenied  -> 403 Forbidden
ClassUnauthenticated   -> 401 Unauthorized
ClassTimeout           -> 504 Gateway Timeout
ClassConflict          -> 409 Conflict
ClassRateLimited       -> 429 Too Many Requests
ClassTemporary         -> 503 Service Unavailable
ClassUnavailable       -> 503 Service Unavailable
ClassInternal          -> 500 Internal Server Error
ClassCancelled         -> 499 Client Closed Request (non-standard)
ClassNotImplemented    -> 501 Not Implemented
ClassSecurity          -> 403 Forbidden
ClassCritical          -> 500 Internal Server Error
ClassExternal          -> 502 Bad Gateway
ClassDataLoss          -> 500 Internal Server Error
ClassResourceExhausted -> 429 Too Many Requests

Error Category Fallback Mappings ΒΆ

When no error class is specified, categories provide fallback mappings:

CategoryUserInput      -> 400 Bad Request
CategoryAuth           -> 401 Unauthorized
CategoryDatabase       -> 500 Internal Server Error
CategoryNetwork        -> 502 Bad Gateway
CategoryAPI            -> 502 Bad Gateway
CategoryBusinessLogic  -> 422 Unprocessable Entity
CategoryCache          -> 503 Service Unavailable
CategoryConfig         -> 500 Internal Server Error
CategoryExternal       -> 502 Bad Gateway
CategorySecurity       -> 403 Forbidden
CategoryPayment        -> 402 Payment Required
CategoryStorage        -> 507 Insufficient Storage
CategoryProcessing     -> 422 Unprocessable Entity
CategoryAnalytics      -> 500 Internal Server Error
CategoryAI             -> 500 Internal Server Error
CategoryMonitoring     -> 500 Internal Server Error
CategoryNotifications  -> 500 Internal Server Error
CategoryEvents         -> 500 Internal Server Error

Basic Usage ΒΆ

// Using error classes
err := erro.New("user not found", erro.ClassNotFound)
statusCode := erro.HTTPCode(err) // Returns 404

err := erro.New("invalid email format", erro.ClassValidation)
statusCode := erro.HTTPCode(err) // Returns 400

// Using error categories as fallback
err := erro.New("database connection failed", erro.CategoryDatabase)
statusCode := erro.HTTPCode(err) // Returns 500

REST API Error Handling ΒΆ

Build consistent REST API error responses:

// Validation errors -> 400 Bad Request
err := erro.New("validation failed",
    "field", "email",
    "reason", "invalid format",
    erro.ClassValidation,
)
statusCode := erro.HTTPCode(err) // 400

// Authentication errors -> 401 Unauthorized
err := erro.New("invalid credentials",
    "login_attempt", 3,
    erro.ClassUnauthenticated,
)
statusCode := erro.HTTPCode(err) // 401

// Authorization errors -> 403 Forbidden
err := erro.New("insufficient permissions",
    "required_role", "admin",
    "user_role", "user",
    erro.ClassPermissionDenied,
)
statusCode := erro.HTTPCode(err) // 403

// Resource not found -> 404 Not Found
err := erro.New("user not found",
    "user_id", 12345,
    erro.ClassNotFound,
)
statusCode := erro.HTTPCode(err) // 404

// Rate limiting -> 429 Too Many Requests
err := erro.New("rate limit exceeded",
    "limit", 100,
    "window", "1h",
    erro.ClassRateLimited,
)
statusCode := erro.HTTPCode(err) // 429

Middleware Integration ΒΆ

Use with HTTP middleware for centralized error handling:

func ErrorMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if err := recover(); err != nil {
                var httpErr error
                if e, ok := err.(error); ok {
                    httpErr = e
                } else {
                    httpErr = fmt.Errorf("panic: %v", err)
                }

                statusCode := erro.HTTPCode(httpErr)
                http.Error(w, httpErr.Error(), statusCode)
            }
        }()
        next.ServeHTTP(w, r)
    })
}

Some Notes ΒΆ

- If the error is nil, it returns 200 OK - If the error is not an Error, it returns 500 Internal Server Error - If the error is an Error, it returns the appropriate HTTP status code based on the error class and category

func ID ΒΆ

func ID(id string) errorOpt

ID sets a custom identifier for the error.

func Is ΒΆ

func Is(err error, target error) (ok bool)

Is reports whether any error in err's chain matches target. It is a drop-in replacement for the standard `errors.Is` function.

func Join ΒΆ

func Join(errs ...error) error

Join returns an error that wraps the given errors. Any nil error values are discarded. It is a drop-in replacement for the standard `errors.Join` function.

func LogError ΒΆ

func LogError(err error, logFunc func(message string, fields ...any), optFuncs ...LogOption)

LogError executes a callback with the error message and structured fields, allowing for integration with any logging library.

If the error is not an Error, it logs the error message directly.

Example:

erro.LogError(err, func(message string, fields ...any) {
    myLogger.Error(message, fields...)
})

func LogErrorWithOptions ΒΆ

func LogErrorWithOptions(err error, logFunc func(message string, fields ...any), opts LogOptions)

LogErrorWithOptions executes a callback with the error message and structured fields, allowing for integration with any logging library.

If the error is not an Error, it logs the error message directly.

Example:

erro.LogErrorWithOptions(err, func(message string, fields ...any) {
    myLogger.Error(message, fields...)
}, erro.LogOptions{
    IncludeUserFields: true,
})

func LogFields ΒΆ

func LogFields(err error, optFuncs ...LogOption) []any

LogFields returns a slice of alternating key-value pairs for structured logging, extracted from the given error.

This is useful for integrating with logging libraries like `slog` that accept key-value pairs.

When option functions are provided, they are applied to a zero LogOptions value (not to DefaultLogOptions), so only the explicitly enabled parts are included and FieldNamePrefix is empty unless set with WithFieldNamePrefix. Field values are passed through as typed values without truncation β€” rendering is the logger's job.

Example:

slog.Error("something went wrong", erro.LogFields(err)...)

func LogFieldsMap ΒΆ

func LogFieldsMap(err error, optFuncs ...LogOption) map[string]any

LogFieldsMap returns a map of field key-value pairs for structured logging, extracted from the given error.

This is useful for integrating with logging libraries like `logrus` that accept a map of fields.

Example:

logrus.WithFields(erro.LogFieldsMap(err)).Error("something went wrong")

func LogFieldsMapWithOptions ΒΆ

func LogFieldsMapWithOptions(err error, opts LogOptions) map[string]any

LogFieldsMapWithOptions returns a map of field key-value pairs for structured logging, extracted from the given error.

This is useful for integrating with logging libraries like `logrus` that accept a map of fields.

Example:

logrus.WithFields(erro.LogFieldsMapWithOptions(err, erro.LogOptions{
    IncludeUserFields: true,
})).Error("something went wrong")

func LogFieldsWithOptions ΒΆ

func LogFieldsWithOptions(err error, opts LogOptions) []any

LogFieldsWithOptions returns a slice of alternating key-value pairs for structured logging, extracted from the given error.

This is useful for integrating with logging libraries like `slog` that accept key-value pairs.

Example:

slog.Error("something went wrong", erro.LogFieldsWithOptions(err, erro.LogOptions{
    IncludeUserFields: true,
})...)

func RecordMetrics ΒΆ

func RecordMetrics(m ErrorMetrics) errorWork

RecordMetrics records the error with a metrics collector. A panic in the ErrorMetrics implementation propagates to the New/Wrap caller.

func RecordSpan ΒΆ

func RecordSpan(s TraceSpan) errorWork

RecordSpan records the error in a tracing span. Redacted field values are replaced with the placeholder before being passed to the span. A panic in the TraceSpan implementation propagates to the New/Wrap caller.

func Retryable ΒΆ

func Retryable() errorOpt

Retryable marks the error as retryable.

func SendEvent ΒΆ

func SendEvent(ctx context.Context, d EventDispatcher) errorWork

SendEvent sends the error to an event dispatcher. A panic in the EventDispatcher implementation propagates to the New/Wrap caller.

func Shutdown ΒΆ

func Shutdown(ctx context.Context, err *error, sd func(ctx context.Context) error, msg string, fields ...any)

Shutdown is a utility function that executes a shutdown function and wraps any resulting error. It is intended for use in cleanup operations.

If the shutdown function is nil, it does nothing. If the shutdown function returns an error, it will be wrapped with the provided message and fields.

Example:

func (s *Server) Stop(ctx context.Context) (err error) {
    defer erro.Shutdown(ctx, &err, s.grpcServer.GracefulStop, "failed to stop gRPC server")
    // ... other shutdown logic
}

func StackTrace ΒΆ

func StackTrace(c ...*StackTraceConfig) errorOpt

StackTrace captures a stack trace for the error.

func StackTraceWithSkip ΒΆ

func StackTraceWithSkip(skip int, c ...*StackTraceConfig) errorOpt

StackTraceWithSkip captures a stack trace, skipping a specified number of caller frames (erro's own construction frames are always excluded).

func Unwrap ΒΆ

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. It is a drop-in replacement for the standard `errors.Unwrap` function.

Types ΒΆ

type Error ΒΆ

type Error interface {
	// error interface
	error
	fmt.Formatter
	json.Marshaler
	json.Unmarshaler
	Is(target error) bool
	As(target any) bool
	Unwrap() error

	// Metadata
	ID() string
	Class() ErrorClass
	Category() ErrorCategory
	Severity() ErrorSeverity
	IsRetryable() bool
	Message() string
	Fields() []any
	Span() TraceSpan
	Created() time.Time
	LogFields(opts ...LogOptions) []any
	LogFieldsMap(opts ...LogOptions) map[string]any

	// Wrapping
	BaseError() Error
	AllFields() []any

	// Stack trace
	Stack() Stack
}

Error represents the common interface for all erro errors.

func ExtractError ΒΆ

func ExtractError(err error) Error

ExtractError ensures that an error can be treated as an Error.

If the given error is already an Error, it is returned as is. If the error merely contains an Error somewhere in its chain, that inner error is returned (outer non-erro layers are not represented in the result). If it's a standard error, it's wrapped in a new Error so that it can be used with the features of this package. If the error is nil, it returns nil.

func New ΒΆ

func New(message string, fields ...any) Error

New creates a new Error with a message and optional structured metadata.

This is the primary function for creating rich, structured errors with comprehensive context and metadata. The returned error implements the standard error interface while providing extensive additional functionality for structured logging, error classification, stack traces, tracing integration, and more.

Basic Usage ΒΆ

err := erro.New("user not found")
err := erro.New("connection failed", "host", "localhost", "port", 5432)

Error Classification ΒΆ

Classify errors using predefined classes, categories, and severity levels:

err := erro.New("invalid email format",
    erro.ClassValidation,        // Error class for HTTP status mapping
    erro.CategoryUserInput,      // Error category for organization
    erro.SeverityLow,           // Severity level for prioritization
)

Structured Logging ΒΆ

Add context through key-value fields that integrate seamlessly with structured loggers:

err := erro.New("database query failed",
    "table", "users",
    "operation", "SELECT",
    "duration_ms", 1500,
    "rows_affected", 0,
)

// Use with slog
slog.Error("Operation failed", erro.LogFields(err)...)

// Use with logrus
logrus.WithFields(erro.LogFieldsMap(err)).Error("Operation failed")

Advanced Configuration ΒΆ

Use functional options for advanced error configuration:

err := erro.New("payment processing failed",
    "amount", 29.99,
    "currency", "USD",
    "merchant_id", "merchant_123",

    erro.ID("payment_error_001"),        // Custom error ID for tracking
    erro.Retryable(),                    // Mark as retryable for retry logic
    erro.StackTrace(),                   // Capture stack trace for debugging
    erro.ClassExternal,                  // External service error
    erro.CategoryPayment,                // Payment-related error
    erro.SeverityCritical,              // Critical severity level

    erro.RecordSpan(span),              // Record in tracing span
    erro.RecordMetrics(metricsCollector), // Send to metrics system
    erro.SendEvent(ctx, eventDispatcher), // Dispatch error event
    erro.Formatter(customFormatter),     // Custom error message formatting
)

JSON Serialization ΒΆ

Errors can be serialized for API responses or database storage:

jsonData, _ := json.Marshal(err)
// Contains: id, class, category, severity, message, fields, stack_trace, etc.

Format Verb Support ΒΆ

The message supports format verbs when additional arguments are provided:

err := erro.New("user %s not found in database %s", "john_doe", "users_db",
    "query_time_ms", 150,
    erro.ClassNotFound,
)
// Message becomes: "user john_doe not found in database users_db"

Some Notes ΒΆ

- Stack traces are captured only when explicitly requested with StackTrace or StackTraceWithSkip - Field values are truncated to prevent memory exhaustion - Error IDs are automatically generated for tracking without performance impact - Structured fields are validated and limited to prevent DoS attacks

Thread Safety ΒΆ

Individual errors are immutable after creation and safe for concurrent use. For collecting multiple errors concurrently, use NewSafeList or NewSafeSet.

func Wrap ΒΆ

func Wrap(err error, message string, fields ...any) Error

Wrap wraps an existing error with additional context, message, and optional metadata.

This function preserves the original error while adding a new layer of context, making it essential for error propagation across application layers. The wrapped error maintains full access to all original metadata while allowing additional context to be attached at each layer.

If the error to be wrapped is nil, Wrap returns nil, making it safe to use in conditional error handling patterns without explicit nil checks.

The wrap depth is limited to MaxWrapDepth: once a chain reaches that many erro layers, Wrap returns the existing error unchanged instead of adding another layer, keeping traversal costs bounded.

Basic Usage ΒΆ

if err != nil {
    return erro.Wrap(err, "failed to process user request")
}

// With additional context
if err != nil {
    return erro.Wrap(err, "database query failed",
        "table", "users",
        "operation", "UPDATE",
    )
}

Advanced Wrapping Features ΒΆ

Enhance wrapped errors with comprehensive metadata and integrations:

err := erro.Wrap(dbErr, "user authentication failed",
    "username", username,
    "login_attempt", attemptCount,
    "ip_address", clientIP,
    "user_agent", erro.Redact(userAgent), // Redact potentially sensitive data

    erro.ClassUnauthenticated,           // Authentication failure
    erro.CategoryAuth,                   // Authentication category
    erro.SeverityMedium,                // Medium severity
    erro.ID("auth_failure_001"),         // Custom error ID for tracking

    erro.StackTrace(),                   // Capture new stack trace at wrap point
    erro.RecordSpan(span),              // Record in distributed tracing
    erro.RecordMetrics(authMetrics),     // Send to authentication metrics
    erro.SendEvent(ctx, securityEvents), // Dispatch to security monitoring
)

Format Verb Support ΒΆ

Use format verbs in wrap messages for dynamic context:

err := erro.Wrap(originalErr, "failed to process %s for user %d",
    operation, userID,
    "retry_count", retryCount,
    "processing_time_ms", duration.Milliseconds(),
)

Error Chain Inspection ΒΆ

Access the complete error chain and metadata:

wrappedErr := erro.Wrap(originalErr, "service layer failure")

// Access original error
originalErr := errors.Unwrap(wrappedErr)

// Check error types in chain
if errors.Is(wrappedErr, sql.ErrNoRows) {
    // Handle specific database error
}

// Access all accumulated fields from error chain
allFields := wrappedErr.AllFields()

// Get inherited metadata from original error
errorClass := wrappedErr.Class()        // Inherits from original if not overridden
errorCategory := wrappedErr.Category()  // Inherits from original if not overridden
errorID := wrappedErr.ID()             // Inherits from original error

Performance and Memory Considerations ΒΆ

  • Error wrapping is lightweight and optimized for high-frequency use
  • Original error references are preserved efficiently without deep copying
  • Field values are automatically truncated to prevent memory exhaustion
  • Stack traces are captured only when explicitly requested with StackTrace or StackTraceWithSkip

Thread Safety ΒΆ

Wrapped errors are immutable and safe for concurrent access across goroutines. The wrapping operation itself is thread-safe and can be called concurrently.

type ErrorCategory ΒΆ

type ErrorCategory string

ErrorCategory represents the category of an error.

const (
	// CategoryDatabase indicates a database-related error.
	CategoryDatabase ErrorCategory = "database"
	// CategoryNetwork indicates a network-related error.
	CategoryNetwork ErrorCategory = "network"
	// CategoryOS indicates an operating system-related error.
	CategoryOS ErrorCategory = "os"
	// CategoryAuth indicates an authentication or authorization error.
	CategoryAuth ErrorCategory = "auth"
	// CategorySecurity indicates a security-related error.
	CategorySecurity ErrorCategory = "security"
	// CategoryPayment indicates a payment-related error.
	CategoryPayment ErrorCategory = "payment"
	// CategoryAPI indicates an API-related error.
	CategoryAPI ErrorCategory = "api"
	// CategoryBusinessLogic indicates an error in business logic.
	CategoryBusinessLogic ErrorCategory = "business_logic"
	// CategoryCache indicates a cache-related error.
	CategoryCache ErrorCategory = "cache"
	// CategoryConfig indicates a configuration error.
	CategoryConfig ErrorCategory = "config"
	// CategoryExternal indicates an error from an external service.
	CategoryExternal ErrorCategory = "external"
	// CategoryUserInput indicates an error due to invalid user input.
	CategoryUserInput ErrorCategory = "user_input"
	// CategoryEvents indicates an event-related error.
	CategoryEvents ErrorCategory = "events"
	// CategoryMonitoring indicates a monitoring-related error.
	CategoryMonitoring ErrorCategory = "monitoring"
	// CategoryNotifications indicates a notification-related error.
	CategoryNotifications ErrorCategory = "notifications"
	// CategoryStorage indicates a storage-related error.
	CategoryStorage ErrorCategory = "storage"
	// CategoryProcessing indicates a data processing error.
	CategoryProcessing ErrorCategory = "processing"
	// CategoryAnalytics indicates an analytics-related error.
	CategoryAnalytics ErrorCategory = "analytics"
	// CategoryAI indicates an AI/ML-related error.
	CategoryAI ErrorCategory = "ai"
	// CategoryUnknown represents an unknown error category.
	CategoryUnknown ErrorCategory = ""
)

func (ErrorCategory) String ΒΆ

func (c ErrorCategory) String() string

String returns the string representation of ErrorCategory.

type ErrorClass ΒΆ

type ErrorClass string

ErrorClass represents the class of an error.

const (
	// ClassValidation indicates an error due to invalid input.
	ClassValidation ErrorClass = "validation"
	// ClassNotFound indicates that a resource was not found.
	ClassNotFound ErrorClass = "not_found"
	// ClassAlreadyExists indicates that a resource already exists.
	ClassAlreadyExists ErrorClass = "already_exists"
	// ClassPermissionDenied indicates a permission error.
	ClassPermissionDenied ErrorClass = "permission_denied"
	// ClassUnauthenticated indicates an authentication error.
	ClassUnauthenticated ErrorClass = "unauthenticated"
	// ClassTimeout indicates that an operation timed out.
	ClassTimeout ErrorClass = "timeout"
	// ClassConflict indicates a conflict with the current state of a resource.
	ClassConflict ErrorClass = "conflict"
	// ClassRateLimited indicates that a rate limit has been exceeded.
	ClassRateLimited ErrorClass = "rate_limited"
	// ClassTemporary indicates a temporary error that may be resolved on retry.
	ClassTemporary ErrorClass = "temporary"
	// ClassUnavailable indicates that a service is unavailable.
	ClassUnavailable ErrorClass = "unavailable"
	// ClassInternal indicates a generic internal error.
	ClassInternal ErrorClass = "internal"
	// ClassCancelled indicates that an operation was cancelled.
	ClassCancelled ErrorClass = "cancelled"
	// ClassNotImplemented indicates that a feature is not implemented.
	ClassNotImplemented ErrorClass = "not_implemented"
	// ClassSecurity indicates a security-related error.
	ClassSecurity ErrorClass = "security"
	// ClassCritical indicates a critical, unrecoverable error.
	ClassCritical ErrorClass = "critical"
	// ClassExternal indicates an error from an external service.
	ClassExternal ErrorClass = "external"
	// ClassDataLoss indicates a loss of data.
	ClassDataLoss ErrorClass = "data_loss"
	// ClassResourceExhausted indicates that a resource has been exhausted.
	ClassResourceExhausted ErrorClass = "resource_exhausted"
	// ClassUnknown represents an unknown error class.
	ClassUnknown ErrorClass = ""
)

func (ErrorClass) String ΒΆ

func (c ErrorClass) String() string

String returns the string representation of ErrorClass.

type ErrorMetrics ΒΆ

type ErrorMetrics interface {
	RecordError(err Error)
}

ErrorMetrics is an interface for recording error metrics.

type ErrorSchema ΒΆ

type ErrorSchema struct {
	ID           string         `json:"id" bson:"_id" db:"id"`
	Class        ErrorClass     `json:"class,omitempty" bson:"class,omitempty" db:"class,omitempty"`
	Category     ErrorCategory  `json:"category,omitempty" bson:"category,omitempty" db:"category,omitempty"`
	Severity     ErrorSeverity  `json:"severity,omitempty" bson:"severity,omitempty" db:"severity,omitempty"`
	Created      time.Time      `json:"created,omitempty" bson:"created,omitempty" db:"created,omitempty"`
	Message      string         `json:"message,omitempty" bson:"message,omitempty" db:"message,omitempty"`
	Fields       []any          `json:"fields,omitempty" bson:"fields,omitempty" db:"fields,omitempty"`
	Retryable    bool           `json:"retryable,omitempty" bson:"retryable,omitempty" db:"retryable,omitempty"`
	StackTrace   []StackContext `json:"stack_trace,omitempty" bson:"stack_trace,omitempty" db:"stack_trace,omitempty"`
	TraceID      string         `json:"trace_id,omitempty" bson:"trace_id,omitempty" db:"trace_id,omitempty"`
	SpanID       string         `json:"span_id,omitempty" bson:"span_id,omitempty" db:"span_id,omitempty"`
	ParentSpanID string         `json:"parent_span_id,omitempty" bson:"parent_span_id,omitempty" db:"parent_span_id,omitempty"`
}

ErrorSchema is a serializable representation of an error.

func ErrorToJSON ΒΆ

func ErrorToJSON(err Error) ErrorSchema

ErrorToJSON converts an error to a serializable ErrorSchema struct.

This is useful for sending error details over the network or storing them in a structured format. Sensitive fields are redacted.

type ErrorSeverity ΒΆ

type ErrorSeverity string

ErrorSeverity represents the severity level of an error.

const (
	SeverityCritical ErrorSeverity = "critical"
	SeverityHigh     ErrorSeverity = "high"
	SeverityMedium   ErrorSeverity = "medium"
	SeverityLow      ErrorSeverity = "low"
	SeverityInfo     ErrorSeverity = "info"
	SeverityUnknown  ErrorSeverity = ""
)

Predefined error severity levels.

func (ErrorSeverity) IsCritical ΒΆ

func (s ErrorSeverity) IsCritical() bool

IsCritical returns true if the severity is Critical.

func (ErrorSeverity) IsHigh ΒΆ

func (s ErrorSeverity) IsHigh() bool

IsHigh returns true if the severity is High.

func (ErrorSeverity) IsInfo ΒΆ

func (s ErrorSeverity) IsInfo() bool

IsInfo returns true if the severity is Info.

func (ErrorSeverity) IsLow ΒΆ

func (s ErrorSeverity) IsLow() bool

IsLow returns true if the severity is Low.

func (ErrorSeverity) IsMedium ΒΆ

func (s ErrorSeverity) IsMedium() bool

IsMedium returns true if the severity is Medium.

func (ErrorSeverity) IsUnknown ΒΆ

func (s ErrorSeverity) IsUnknown() bool

IsUnknown returns true if the severity is Unknown.

func (ErrorSeverity) IsValid ΒΆ

func (s ErrorSeverity) IsValid() bool

IsValid checks if the severity is one of the predefined values.

func (ErrorSeverity) Label ΒΆ

func (s ErrorSeverity) Label() string

Label returns a short, human-readable label for the severity level.

func (ErrorSeverity) String ΒΆ

func (s ErrorSeverity) String() string

String returns the string representation of ErrorSeverity.

type ErrorTemplate ΒΆ

type ErrorTemplate struct {
	// contains filtered or unexported fields
}

ErrorTemplate represents a template for creating errors with predefined metadata.

func NewTemplate ΒΆ

func NewTemplate(messageTemplate string, opts ...any) *ErrorTemplate

NewTemplate creates a new error template with a message and predefined options.

func (*ErrorTemplate) New ΒΆ

func (t *ErrorTemplate) New(fields ...any) Error

New creates an error from the template.

func (*ErrorTemplate) Wrap ΒΆ

func (t *ErrorTemplate) Wrap(originalErr error, fields ...any) Error

Wrap wraps an existing error with the template's message and options. If the error is nil, Wrap returns nil, mirroring Wrap.

type EventDispatcher ΒΆ

type EventDispatcher interface {
	SendEvent(ctx context.Context, err Error)
}

EventDispatcher is an interface for sending error events.

type FormatErrorFunc ΒΆ

type FormatErrorFunc func(err Error) string

FormatErrorFunc is a function that formats an error into a string.

func GetFormatErrorWithFullContext ΒΆ

func GetFormatErrorWithFullContext(optFuncs ...LogOption) FormatErrorFunc

GetFormatErrorWithFullContext returns a FormatErrorFunc that formats an error with full context, including log fields.

func GetFormatErrorWithFullContextBase ΒΆ

func GetFormatErrorWithFullContextBase(optFuncs ...LogOption) FormatErrorFunc

GetFormatErrorWithFullContextBase returns a FormatErrorFunc that formats an error with full context.

type KeyGetterFunc ΒΆ

type KeyGetterFunc func(err error) string

KeyGetterFunc is a function that generates a key for an error, used for deduplication.

var (
	// MessageKeyGetter generates a key based on the error's message without fields.
	MessageKeyGetter KeyGetterFunc = func(err error) string {
		if err == nil {
			return ""
		}
		if erroErr, ok := err.(Error); ok {
			return erroErr.Message()
		}
		var erroErr Error
		if As(err, &erroErr) {
			return erroErr.Message()
		}
		return err.Error()
	}
	// IDKeyGetter generates a key based on the error's ID.
	IDKeyGetter KeyGetterFunc = func(err error) string {
		if err == nil {
			return ""
		}
		if erroErr, ok := err.(Error); ok {
			return erroErr.ID()
		}
		var erroErr Error
		if As(err, &erroErr) {
			return erroErr.ID()
		}
		return err.Error()
	}
	// ErrorKeyGetter generates a key based on the error's string representation (err.Error()).
	ErrorKeyGetter KeyGetterFunc = func(err error) string {
		if err == nil {
			return ""
		}
		return err.Error()
	}
)

Key getter functions for deduplication

type List ΒΆ

type List struct {
	// contains filtered or unexported fields
}

List collects multiple errors and provides a fluent API for adding and configuring them. It is not thread-safe. For a thread-safe version, see SafeList.

func NewList ΒΆ

func NewList(capacity ...int) *List

NewList creates a new error list with an optional initial capacity.

func (*List) Add ΒΆ

func (g *List) Add(err error) *List

Add adds an error to the list. If the error is not already an Error, it is converted to one. If the error is nil, it is ignored.

func (*List) Clear ΒΆ

func (g *List) Clear() *List

Clear removes all errors from the list.

func (*List) Copy ΒΆ

func (g *List) Copy() *List

Copy returns a shallow copy of the list.

func (*List) Empty ΒΆ

func (g *List) Empty() bool

Empty returns true if the list contains no errors.

func (*List) Err ΒΆ

func (g *List) Err() error

Err returns a single error representing all errors in the list. If the list is empty, it returns nil. If the list contains a single error, that error is returned. If the list contains multiple errors, they are combined into a multi-error.

func (*List) Errors ΒΆ

func (g *List) Errors() []error

Errors returns a slice of all errors in the list as standard `error` interfaces.

func (*List) Errs ΒΆ

func (g *List) Errs() []Error

Errs returns a slice of all errors in the list as Error interfaces. The returned slice is a copy and can be safely retained by the caller.

func (*List) First ΒΆ

func (g *List) First() Error

First returns the first error in the list, or nil if the list is empty.

func (*List) Last ΒΆ

func (g *List) Last() Error

Last returns the last error in the list, or nil if the list is empty.

func (*List) Len ΒΆ

func (g *List) Len() int

Len returns the number of errors in the list.

func (*List) New ΒΆ

func (g *List) New(message string, meta ...any) *List

New creates a new error with the given message and metadata, and adds it to the list.

func (*List) NotEmpty ΒΆ

func (g *List) NotEmpty() bool

NotEmpty returns true if the list contains at least one error.

func (*List) Remove ΒΆ

func (g *List) Remove(i int) bool

Remove removes an error at the specified index from the list. It returns true if the removal was successful, and false otherwise.

func (*List) RemoveError ΒΆ

func (g *List) RemoveError(err error) bool

RemoveError removes the first error that matches the given error by ID. It returns true if an error was removed, and false otherwise.

func (*List) Wrap ΒΆ

func (g *List) Wrap(err error, message string, meta ...any) *List

Wrap wraps an existing error with the given message and metadata, and adds it to the list. If the error is nil, it is ignored.

type LogOption ΒΆ

type LogOption func(*LogOptions)

LogOption is a function that configures logging options.

func MergeLogOpts ΒΆ

func MergeLogOpts(opts []LogOption, addsOpts ...LogOption) []LogOption

MergeLogOpts merges multiple slices of LogOption functions into one.

func WithCategory ΒΆ

func WithCategory(include ...bool) LogOption

WithCategory returns a LogOption to enable or disable the error category field.

func WithCreatedTime ΒΆ

func WithCreatedTime(include ...bool) LogOption

WithCreatedTime returns a LogOption to enable or disable the creation timestamp field.

func WithErrorMessage ΒΆ added in v1.0.1

func WithErrorMessage(include ...bool) LogOption

WithErrorMessage returns a LogOption to enable or disable the error message field.

func WithFieldNamePrefix ΒΆ

func WithFieldNamePrefix(prefix string) LogOption

WithFieldNamePrefix returns a LogOption to set the field name prefix.

func WithFile ΒΆ

func WithFile(include ...bool) LogOption

WithFile returns a LogOption to enable or disable the file name field.

func WithFunction ΒΆ

func WithFunction(include ...bool) LogOption

WithFunction returns a LogOption to enable or disable the function name field.

func WithID ΒΆ

func WithID(include ...bool) LogOption

WithID returns a LogOption to enable or disable the error ID field.

func WithLine ΒΆ

func WithLine(include ...bool) LogOption

WithLine returns a LogOption to enable or disable the line number field.

func WithPackage ΒΆ

func WithPackage(include ...bool) LogOption

WithPackage returns a LogOption to enable or disable the package name field.

func WithRetryable ΒΆ

func WithRetryable(include ...bool) LogOption

WithRetryable returns a LogOption to enable or disable the retryable flag field.

func WithSeverity ΒΆ

func WithSeverity(include ...bool) LogOption

WithSeverity returns a LogOption to enable or disable the error severity field.

func WithStack ΒΆ

func WithStack(include ...bool) LogOption

WithStack returns a LogOption to enable or disable the full stack trace field.

func WithStackFormat ΒΆ

func WithStackFormat(format StackFormat) LogOption

WithStackFormat returns a LogOption to set the stack trace format.

func WithTracing ΒΆ

func WithTracing(include ...bool) LogOption

WithTracing returns a LogOption to enable or disable tracing fields.

func WithUserFields ΒΆ

func WithUserFields(include ...bool) LogOption

WithUserFields returns a LogOption to enable or disable user-defined fields.

type LogOptions ΒΆ

type LogOptions struct {
	// IncludeErrorMessage determines whether to include the error message.
	IncludeErrorMessage bool

	// IncludeUserFields determines whether to include user-defined fields.
	IncludeUserFields bool

	// IncludeID determines whether to include the error ID.
	IncludeID bool
	// IncludeCategory determines whether to include the error category.
	IncludeCategory bool
	// IncludeSeverity determines whether to include the error severity.
	IncludeSeverity bool
	// IncludeRetryable determines whether to include the retryable flag.
	IncludeRetryable bool
	// IncludeTracing determines whether to include tracing information (TraceID, SpanID).
	IncludeTracing bool

	// IncludeCreatedTime determines whether to include the error creation timestamp.
	IncludeCreatedTime bool

	// IncludeFunction determines whether to include the function name from the stack trace.
	IncludeFunction bool
	// IncludePackage determines whether to include the package name from the stack trace.
	IncludePackage bool
	// IncludeFile determines whether to include the file name from the stack trace.
	IncludeFile bool
	// IncludeLine determines whether to include the line number from the stack trace.
	IncludeLine bool
	// IncludeStack determines whether to include the full stack trace.
	IncludeStack bool

	// StackFormat defines how stack traces should be formatted.
	StackFormat StackFormat

	// FieldNamePrefix is a prefix added to all field names. Default is "error_".
	FieldNamePrefix string
}

LogOptions controls which fields are included in logging output.

func (*LogOptions) ApplyOptions ΒΆ

func (opts *LogOptions) ApplyOptions(optFuncs ...LogOption) LogOptions

ApplyOptions applies a set of option functions to LogOptions.

type RedactedValue ΒΆ

type RedactedValue struct {
	Value any
}

RedactedValue is a wrapper for a value that should be redacted in logs.

func Redact ΒΆ

func Redact(value any) RedactedValue

Redact wraps a value to mark it as sensitive. Its content will be replaced with RedactedPlaceholder when the error is formatted as a string or JSON.

func (RedactedValue) GoString ΒΆ added in v1.0.3

func (r RedactedValue) GoString() string

GoString implements fmt.GoStringer so the wrapped value is never revealed through the %#v verb.

func (RedactedValue) MarshalJSON ΒΆ added in v1.0.3

func (r RedactedValue) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler so the wrapped value is never revealed when marshaled to JSON.

func (RedactedValue) String ΒΆ added in v1.0.3

func (r RedactedValue) String() string

String implements fmt.Stringer so the wrapped value is never revealed through fmt verbs like %v and %s.

type SafeList ΒΆ

type SafeList struct {
	// contains filtered or unexported fields
}

SafeList is a thread-safe version of List.

func NewSafeList ΒΆ

func NewSafeList(capacity ...int) *SafeList

NewSafeList creates a new thread-safe error list.

func (*SafeList) Add ΒΆ

func (sl *SafeList) Add(err error) *SafeList

Add adds an error to the list in a thread-safe manner.

func (*SafeList) Clear ΒΆ

func (sl *SafeList) Clear() *SafeList

Clear removes all errors from the list in a thread-safe manner.

func (*SafeList) Copy ΒΆ

func (sl *SafeList) Copy() *SafeList

Copy returns a shallow copy of the list in a thread-safe manner.

func (*SafeList) Empty ΒΆ

func (sl *SafeList) Empty() bool

Empty returns true if the list contains no errors in a thread-safe manner.

func (*SafeList) Err ΒΆ

func (sl *SafeList) Err() error

Err returns a combined error from all errors in the list in a thread-safe manner.

func (*SafeList) Errors ΒΆ

func (sl *SafeList) Errors() []error

Errors returns a slice of all errors in the list as standard `error` interfaces in a thread-safe manner.

func (*SafeList) Errs ΒΆ

func (sl *SafeList) Errs() []Error

Errs returns a slice of all errors in the list as `erro.Error` interfaces in a thread-safe manner.

func (*SafeList) First ΒΆ

func (sl *SafeList) First() Error

First returns the first error in the list in a thread-safe manner.

func (*SafeList) Last ΒΆ

func (sl *SafeList) Last() Error

Last returns the last error in the list in a thread-safe manner.

func (*SafeList) Len ΒΆ

func (sl *SafeList) Len() int

Len returns the number of errors in the list in a thread-safe manner.

func (*SafeList) New ΒΆ

func (sl *SafeList) New(message string, meta ...any) *SafeList

New creates a new error and adds it to the list in a thread-safe manner.

func (*SafeList) NotEmpty ΒΆ

func (sl *SafeList) NotEmpty() bool

NotEmpty returns true if the list contains at least one error in a thread-safe manner.

func (*SafeList) Remove ΒΆ

func (sl *SafeList) Remove(i int) bool

Remove removes an error at the specified index in a thread-safe manner.

func (*SafeList) RemoveError ΒΆ

func (sl *SafeList) RemoveError(err error) bool

RemoveError removes the first error that matches the given error by ID in a thread-safe manner.

func (*SafeList) Wrap ΒΆ

func (sl *SafeList) Wrap(err error, message string, meta ...any) *SafeList

Wrap wraps an existing error and adds it to the list in a thread-safe manner.

type SafeSet ΒΆ

type SafeSet struct {
	// contains filtered or unexported fields
}

SafeSet is a thread-safe version of Set.

func NewSafeSet ΒΆ

func NewSafeSet(capacity ...int) *SafeSet

NewSafeSet creates a new thread-safe error set.

func (*SafeSet) Add ΒΆ

func (ss *SafeSet) Add(err error) *SafeSet

Add adds an error to the set in a thread-safe manner.

func (*SafeSet) Clear ΒΆ

func (ss *SafeSet) Clear() *SafeSet

Clear removes all errors from the set in a thread-safe manner.

func (*SafeSet) Copy ΒΆ

func (ss *SafeSet) Copy() *SafeSet

Copy returns a shallow copy of the set in a thread-safe manner.

func (*SafeSet) Empty ΒΆ

func (ss *SafeSet) Empty() bool

Empty returns true if the set contains no errors in a thread-safe manner.

func (*SafeSet) Err ΒΆ

func (ss *SafeSet) Err() error

Err returns a combined error from all errors in the set in a thread-safe manner.

func (*SafeSet) Errors ΒΆ

func (ss *SafeSet) Errors() []error

Errors returns a slice of all errors in the set as standard `error` interfaces in a thread-safe manner.

func (*SafeSet) Errs ΒΆ

func (ss *SafeSet) Errs() []Error

Errs returns a slice of all errors in the set as `erro.Error` interfaces in a thread-safe manner.

func (*SafeSet) First ΒΆ

func (ss *SafeSet) First() Error

First returns the first error in the set in a thread-safe manner.

func (*SafeSet) Last ΒΆ

func (ss *SafeSet) Last() Error

Last returns the last error in the set in a thread-safe manner.

func (*SafeSet) Len ΒΆ

func (ss *SafeSet) Len() int

Len returns the number of errors in the set in a thread-safe manner.

func (*SafeSet) New ΒΆ

func (ss *SafeSet) New(message string, meta ...any) *SafeSet

New creates a new error and adds it to the set in a thread-safe manner.

func (*SafeSet) NotEmpty ΒΆ

func (ss *SafeSet) NotEmpty() bool

NotEmpty returns true if the set contains at least one error in a thread-safe manner.

func (*SafeSet) Remove ΒΆ

func (ss *SafeSet) Remove(i int) bool

Remove removes an error at the specified index in a thread-safe manner.

func (*SafeSet) RemoveError ΒΆ

func (ss *SafeSet) RemoveError(err error) bool

RemoveError removes the first error that matches the given error by ID in a thread-safe manner.

func (*SafeSet) WithKeyGetter ΒΆ

func (ss *SafeSet) WithKeyGetter(keyGetter KeyGetterFunc) *SafeSet

WithKeyGetter sets the function used to generate deduplication keys for errors in a thread-safe manner.

func (*SafeSet) Wrap ΒΆ

func (ss *SafeSet) Wrap(err error, message string, meta ...any) *SafeSet

Wrap wraps an existing error and adds it to the set in a thread-safe manner.

type Set ΒΆ

type Set struct {
	*List
	// contains filtered or unexported fields
}

Set collects unique errors, deduplicating them based on a configurable key. It is not thread-safe. For a thread-safe version, see SafeSet.

Note: Set embeds List for its accessors. Calling mutating methods directly on the embedded List (e.g. set.List.Add) bypasses deduplication and desyncs the internal counters β€” always use the Set's own methods.

func NewSet ΒΆ

func NewSet(capacity ...int) *Set

NewSet creates a new error set that stores only unique errors, with an optional initial capacity.

func (*Set) Add ΒΆ

func (s *Set) Add(err error) *Set

Add adds an error to the set. If the error is not already an Error, it is converted to one. If the error is nil, it is ignored.

func (*Set) Clear ΒΆ

func (s *Set) Clear() *Set

Clear removes all errors and resets the deduplication map.

func (*Set) Copy ΒΆ

func (s *Set) Copy() *Set

Copy returns a shallow copy of the set.

func (*Set) Err ΒΆ

func (s *Set) Err() error

Err returns a combined error that includes deduplication counts. If the set is empty, it returns nil. If the set contains a single error, that error is returned. If the set contains multiple errors, they are combined into a multi-error.

func (*Set) New ΒΆ

func (s *Set) New(message string, meta ...any) *Set

New creates a new error and adds it to the set.

func (*Set) Remove ΒΆ

func (s *Set) Remove(i int) bool

Remove removes an error and its key from the seen map. It returns true if an error was removed, and false otherwise.

func (*Set) RemoveError ΒΆ

func (s *Set) RemoveError(err error) bool

RemoveError removes an error by its instance and its key from the seen map. It returns true if an error was removed, and false otherwise.

func (*Set) WithKeyGetter ΒΆ

func (s *Set) WithKeyGetter(keyGetter KeyGetterFunc) *Set

WithKeyGetter sets the function used to generate deduplication keys for errors.

func (*Set) Wrap ΒΆ

func (s *Set) Wrap(err error, message string, meta ...any) *Set

Wrap wraps an existing error and adds it to the set. If the error is nil, it is ignored.

type Stack ΒΆ

type Stack []StackFrame

Stack represents a collection of stack frames with enhanced analysis capabilities.

func (Stack) ContainsFunction ΒΆ

func (s Stack) ContainsFunction(functionName string) bool

ContainsFunction returns true if the stack contains a frame with the given function name.

func (Stack) ExtractPackages ΒΆ

func (s Stack) ExtractPackages() []string

ExtractPackages returns unique packages involved in the error.

func (Stack) FilterByPackage ΒΆ

func (s Stack) FilterByPackage(packageName string) Stack

FilterByPackage returns frames that belong to the specified package.

func (Stack) FormatFull ΒΆ

func (s Stack) FormatFull() string

FormatFull returns a detailed formatted stack trace.

func (Stack) GetCallChain ΒΆ

func (s Stack) GetCallChain() []string

GetCallChain returns the call chain of user functions leading to the error.

func (Stack) GetOriginContext ΒΆ

func (s Stack) GetOriginContext() *StackContext

GetOriginContext returns context information about where the error originated.

func (Stack) IsGlobalError ΒΆ

func (s Stack) IsGlobalError() bool

IsGlobalError determines if the stack trace represents a global/init error.

func (Stack) String ΒΆ

func (s Stack) String() string

String returns a formatted string representation of the entire stack.

func (Stack) ToJSON ΒΆ

func (s Stack) ToJSON() []map[string]any

ToJSON returns a JSON-friendly representation of the stack.

func (Stack) ToJSONUserFrames ΒΆ

func (s Stack) ToJSONUserFrames() []map[string]any

ToJSONUserFrames returns a JSON-friendly representation of user frames only.

func (Stack) ToLogFields ΒΆ

func (s Stack) ToLogFields() map[string]any

ToLogFields converts stack context to logging fields.

func (Stack) TopUserFrame ΒΆ

func (s Stack) TopUserFrame() *StackFrame

TopUserFrame returns the topmost user code frame (where the error likely originated).

func (Stack) UserFrames ΒΆ

func (s Stack) UserFrames() Stack

UserFrames returns only the user code frames, filtering out runtime and stdlib.

type StackContext ΒΆ

type StackContext struct {
	Function   string            `json:"function" bson:"function" db:"function"`
	Package    string            `json:"package" bson:"package" db:"package"`
	Module     string            `json:"module" bson:"module" db:"module"`
	File       string            `json:"file" bson:"file" db:"file"`
	Line       int               `json:"line" bson:"line" db:"line"`
	IsUserCode bool              `json:"is_user_code" bson:"is_user_code" db:"is_user_code"`
	Metadata   map[string]string `json:"metadata" bson:"metadata" db:"metadata"`
}

StackContext extracts contextual information from the stack frame.

type StackFormat ΒΆ

type StackFormat int

StackFormat defines how stack traces should be formatted in logs.

const (
	// StackFormatString formats the stack trace as a single string.
	StackFormatString StackFormat = iota
	// StackFormatList formats the stack trace as a list of function calls.
	StackFormatList
	// StackFormatFull formats the stack trace with detailed information.
	StackFormatFull
	// StackFormatJSON formats the stack trace as a JSON object.
	StackFormatJSON
)

type StackFrame ΒΆ

type StackFrame struct {
	Name             string // Function name (e.g., "processPayment")
	FullName         string // Full function name (e.g., "github.com/app/payment.processPayment")
	Package          string // Package name (e.g., "payment")
	File             string // Full file path
	FileName         string // Just the filename (e.g., "payment.go")
	Line             int    // Line number
	StackTraceConfig *StackTraceConfig
}

StackFrame stores a frame's runtime information in a human-readable format, enhanced with additional context for better error diagnostics.

func (StackFrame) FormatFull ΒΆ

func (f StackFrame) FormatFull() string

FormatFull returns a detailed formatted stack frame.

func (StackFrame) GetContext ΒΆ

func (f StackFrame) GetContext() StackContext

GetContext extracts rich context information from the stack frame.

func (StackFrame) IsErroInternal ΒΆ

func (f StackFrame) IsErroInternal() bool

IsErroInternal returns true if this frame is from erro internal functions.

func (StackFrame) IsRuntime ΒΆ

func (f StackFrame) IsRuntime() bool

IsRuntime returns true if this frame is from the Go runtime.

func (StackFrame) IsStandardLibrary ΒΆ

func (f StackFrame) IsStandardLibrary() bool

IsStandardLibrary returns true if this frame is from the Go standard library.

func (StackFrame) IsTest ΒΆ

func (f StackFrame) IsTest() bool

IsTest returns true if this frame is from test code.

func (StackFrame) IsUser ΒΆ

func (f StackFrame) IsUser() bool

IsUser returns true if this frame represents user code (not runtime, stdlib, or erro internal).

func (StackFrame) String ΒΆ

func (f StackFrame) String() string

String returns a formatted representation of the stack frame.

func (StackFrame) ToJSON ΒΆ

func (f StackFrame) ToJSON() map[string]any

ToJSON returns a JSON-friendly representation of the stack frame.

type StackTraceConfig ΒΆ

type StackTraceConfig struct {
	ShowFileNames     bool   // Whether to show file names.
	ShowFullPaths     bool   // Whether to show full file paths.
	PathElements      int    // Number of path elements to include (0 = filename only, -1 = full path).
	ShowFunctionNames bool   // Whether to show function names.
	ShowPackageNames  bool   // Whether to show package names.
	ShowLineNumbers   bool   // Whether to show line numbers.
	ShowAllCodeFrames bool   // Whether to show all types of frames (user, stdlib, etc.).
	FunctionRedacted  string // Placeholder for redacted function names.
	FileNameRedacted  string // Placeholder for redacted file names.
	MaxFrames         int    // Maximum number of frames to show.
}

StackTraceConfig controls what information is included in stack traces.

func DevelopmentStackTraceConfig ΒΆ

func DevelopmentStackTraceConfig() *StackTraceConfig

DevelopmentStackTraceConfig returns a stack trace configuration suitable for development environments.

func ProductionStackTraceConfig ΒΆ

func ProductionStackTraceConfig() *StackTraceConfig

ProductionStackTraceConfig returns a stack trace configuration suitable for production environments.

func StrictStackTraceConfig ΒΆ

func StrictStackTraceConfig() *StackTraceConfig

StrictStackTraceConfig returns a strict privacy stack trace configuration.

type TraceSpan ΒΆ

type TraceSpan interface {
	RecordError(err Error)
	SetAttributes(attributes ...any)
	TraceID() string
	SpanID() string
	ParentSpanID() string
}

TraceSpan is an interface for recording errors in a trace span.

Directories ΒΆ

Path Synopsis
examples
basic command
collections command
http command
logging command
stack command
templates command

Jump to

Keyboard shortcuts

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