xerrors

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 4 Imported by: ? modules, 0 packages

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

xerrors

A structured error handling package that wraps standard Go errors with business-level contexts, such as String Codes (e.g., UNAUTHORIZED) and HTTP Status Codes. This makes it trivial to map backend errors directly to REST API responses.

Key Features
  • Structured Errors: Every error carries a Code, Message, and HTTPStatus.
  • Error Wrapping: Chain errors together using xerrors.Wrap while preserving the root cause.
  • Structured Fields: Attach context such as {"user_id": "7"} with NewWithFields and WrapWithFields.
  • Stack Traces: New, NewWithFields, Wrap and WrapWithFields capture up to 32 frames.
  • Pre-defined Common Errors: Ready-to-use variables like ErrNotFound, ErrUnauthorized, and ErrInternal.
  • Match by Code: errors.Is(err, xerrors.ErrNotFound) is true for any CustomError with code NOT_FOUND, including wrapped ones.
  • Standard Library Compatibility: Proxies standard errors.Is, errors.As, and errors.Join for convenience.
Quick Start
1. Using Pre-defined Errors

The package comes with many standard HTTP errors out of the box.

import "github.com/thanhbvha/go-common/v2/xerrors"

func GetUser(id string) (*User, error) {
    if id == "" {
        return nil, xerrors.ErrBadRequest
    }
    
    user, err := db.Find(id)
    if err != nil {
        if db.IsNotFound(err) {
            // Returns a 404 NOT_FOUND error
            return nil, xerrors.ErrNotFound 
        }
        return nil, xerrors.ErrInternal
    }
    return user, nil
}

These variables are shared sentinels. Do not modify their fields. Their stack was captured when the package initialized, so it does not show where you returned them. When you need a useful stack, return xerrors.New(...) or xerrors.Wrap(err, ...) instead. Check for them with errors.Is, which compares the Code:

wrapped := xerrors.Wrap(sql.ErrNoRows, "NOT_FOUND", "user missing", 404)
errors.Is(wrapped, xerrors.ErrNotFound) // true: same code
errors.Is(wrapped, sql.ErrNoRows)       // true: the cause is kept
2. Creating Custom Errors

You can define your own domain-specific errors.

var ErrInsufficientFunds = xerrors.New("INSUFFICIENT_FUNDS", "You do not have enough balance", 400)
var ErrAccountLocked = xerrors.New("ACCOUNT_LOCKED", "Your account has been temporarily locked", 403)

func Withdraw(amount int) error {
    return ErrInsufficientFunds
}
3. Wrapping Existing Errors

If a lower-level component fails (like a database or network call), wrap it to add HTTP context without losing the original stack/cause.

func QueryData() error {
    err := db.Query(...)
    if err != nil {
        return xerrors.Wrap(err, "DB_QUERY_FAILED", "Failed to retrieve data from database", 500)
    }
    return nil
}
4. Mapping a Safe Public Response

Do not serialize err.Error(): wrapped causes are diagnostic. Use the shared response mapper so unknown errors, invalid statuses and all 5xx messages are masked consistently.

func ErrorMiddleware(c *fiber.Ctx, err error) error {
    requestID, _ := c.Locals("request_id").(string)
    public := response.FromError(err, requestID)
    return c.Status(public.Code).JSON(public)
}
5. Adding Context Fields
return xerrors.WrapWithFields(err, "USER_LOAD_FAILED", "Could not load user", 500,
    map[string]any{"user_id": id})

Fields are for logs and diagnostics. The web mapper never sends them to clients. The web error handlers log the code, cause and stack (StackTraceString) when the status is 5xx; read the fields yourself with GetFields if you want them in your own log record.

Key Types & Functions
Symbol Description
CustomError The underlying struct implementing the error interface. Is matches by Code.
New(code, msg, status) Create a new structured error.
NewWithFields(code, msg, status, fields) Create a structured error with context fields.
Wrap(err, code, msg, status) Wrap an existing error with structured context. Returns nil for a nil error.
WrapWithFields(err, code, msg, status, fields) Wrap with context fields. Returns nil for a nil error.
StackTraceString(err) Formats the captured stack as multi-line text, or "" if none.
GetFields(err) Returns the context fields, or nil.
HTTPStatusCode(err) Safely extracts the HTTPStatus from an error (returns 500 if unknown).
GetCode(err) Safely extracts the Code from an error (returns "INTERNAL_ERROR" if unknown).
Is(err, target) Proxy for standard errors.Is.
As(err, target) Proxy for standard errors.As.
Join(errs...) Proxy for standard errors.Join.

Public transport policy

Error() remains diagnostic and includes the cause; do not send it to clients. The web error mapper publishes only CustomError.Message for valid 4xx errors, masking causes and all 5xx/unknown errors. HTTPStatusCode normalizes invalid statuses on non-nil errors to 500. Keep public messages free of credentials and personal data; retain diagnostic context in the cause and structured fields.

Because 5xx messages are masked for clients, the web error handlers log the real error server-side (see the web README).

Documentation

Overview

Package xerrors provides a structured error handling mechanism for HTTP applications.

It extends the standard Go error interface by embedding HTTP status codes, application-specific string codes, and error chaining (cause) capabilities. This allows handlers to return rich errors that the global error handler can automatically translate into correct HTTP responses.

Basic usage:

if err != nil {
	return xerrors.Wrap(err, "DB_ERROR", "failed to query user", 500)
}
if user == nil {
	return xerrors.New("USER_NOT_FOUND", "user does not exist", 404)
}

Index

Constants

View Source
const (
	StatusOK                  = 200
	StatusCreated             = 201
	StatusAccepted            = 202
	StatusNoContent           = 204
	StatusBadRequest          = 400
	StatusUnauthorized        = 401
	StatusForbidden           = 403
	StatusNotFound            = 404
	StatusMethodNotAllowed    = 405
	StatusNotAcceptable       = 406
	StatusRequestTimeout      = 408
	StatusConflict            = 409
	StatusPayloadTooLarge     = 413
	StatusUnsupportedMedia    = 415
	StatusUnprocessableEntity = 422
	StatusTooManyRequests     = 429
	StatusInternalServerError = 500
	StatusNotImplemented      = 501
	StatusBadGateway          = 502
	StatusServiceUnavailable  = 503
	StatusGatewayTimeout      = 504
)

Standard HTTP status codes, mapped from net/http for convenience without importing it

Variables

View Source
var (
	// 4xx Client Errors
	ErrBadRequest          = New("BAD_REQUEST", "Invalid request parameters", StatusBadRequest)
	ErrUnauthorized        = New("UNAUTHORIZED", "Authentication required", StatusUnauthorized)
	ErrInvalidToken        = New("INVALID_TOKEN", "Token is invalid or expired", StatusUnauthorized)
	ErrForbidden           = New("FORBIDDEN", "You do not have permission to access this resource", StatusForbidden)
	ErrNotFound            = New("NOT_FOUND", "Resource not found", StatusNotFound)
	ErrMethodNotAllowed    = New("METHOD_NOT_ALLOWED", "HTTP method not allowed for this resource", StatusMethodNotAllowed)
	ErrNotAcceptable       = New("NOT_ACCEPTABLE", "Requested format is not supported", StatusNotAcceptable)
	ErrRequestTimeout      = New("REQUEST_TIMEOUT", "Request took too long to process", StatusRequestTimeout)
	ErrConflict            = New("CONFLICT", "Resource already exists or conflict occurred", StatusConflict)
	ErrPayloadTooLarge     = New("PAYLOAD_TOO_LARGE", "Request payload exceeds the maximum allowed size", StatusPayloadTooLarge)
	ErrUnsupportedMedia    = New("UNSUPPORTED_MEDIA_TYPE", "Media type is not supported", StatusUnsupportedMedia)
	ErrUnprocessableEntity = New("UNPROCESSABLE_ENTITY", "Data validation failed", StatusUnprocessableEntity)
	ErrTooManyRequests     = New("TOO_MANY_REQUESTS", "Rate limit exceeded, please try again later", StatusTooManyRequests)

	// 5xx Server Errors
	ErrInternal           = New("INTERNAL_ERROR", "An unexpected internal error occurred", StatusInternalServerError)
	ErrNotImplemented     = New("NOT_IMPLEMENTED", "This feature is not yet implemented", StatusNotImplemented)
	ErrBadGateway         = New("BAD_GATEWAY", "Invalid response from upstream server", StatusBadGateway)
	ErrServiceUnavailable = New("SERVICE_UNAVAILABLE", "Service is currently unavailable", StatusServiceUnavailable)
	ErrGatewayTimeout     = New("GATEWAY_TIMEOUT", "Upstream server timed out", StatusGatewayTimeout)
)

Common error variables that can be reused across services.

They are shared sentinels: match them with errors.Is (which compares Code) and never modify their fields. Their stack trace was captured at package init, so it does not point at the call site. To get a useful stack, return xerrors.Wrap(err, ...) or xerrors.New(...) instead of the sentinel itself.

Functions

func As

func As(err error, target interface{}) bool

As is a convenience wrapper around standard errors.As

func GetCode

func GetCode(err error) string

GetCode extracts the string code from an error.

func GetFields

func GetFields(err error) map[string]any

GetFields extracts the structured fields map from an error. Returns nil if the error is not a *CustomError.

func HTTPStatusCode

func HTTPStatusCode(err error) int

HTTPStatusCode extracts the HTTP status code from an error. If it's a CustomError, it returns its status. Otherwise, 500.

func Is

func Is(err, target error) bool

Is is a convenience wrapper around standard errors.Is

func Join

func Join(errs ...error) error

Join is a convenience wrapper around standard errors.Join (Go 1.20+)

func New

func New(code, message string, httpStatus int) error

New creates a new CustomError with a captured stack trace.

func NewWithFields

func NewWithFields(code, message string, httpStatus int, fields map[string]any) error

NewWithFields creates a new CustomError with structured context fields.

Example:

return xerrors.NewWithFields("USER_NOT_FOUND", "user not found", 404,
    map[string]any{"user_id": id})

func StackTraceString

func StackTraceString(err error) string

StackTraceString formats the stack trace as a human-readable multi-line string. Returns "" if no stack is captured.

func Wrap

func Wrap(err error, code, message string, httpStatus int) error

Wrap wraps an existing error with a CustomError and a captured stack trace.

func WrapWithFields

func WrapWithFields(err error, code, message string, httpStatus int, fields map[string]any) error

WrapWithFields is Wrap with structured context fields.

Types

type CustomError

type CustomError struct {
	Code       string
	Message    string
	HTTPStatus int
	Cause      error
	Fields     map[string]any // structured context (e.g. {"user_id": "123"})
	// contains filtered or unexported fields
}

CustomError represents a standard application error with optional stack trace.

func (*CustomError) Error

func (e *CustomError) Error() string

Error implements the standard error interface.

func (*CustomError) Is

func (e *CustomError) Is(target error) bool

Is makes errors.Is match any *CustomError with the same Code, so errors.Is(Wrap(err, "NOT_FOUND", ...), ErrNotFound) is true.

func (*CustomError) StackTrace

func (e *CustomError) StackTrace() []Frame

StackTrace returns the captured call stack frames, filtering out runtime internals.

func (*CustomError) Unwrap

func (e *CustomError) Unwrap() error

Unwrap implements the interface for errors.Is and errors.As.

type Frame

type Frame struct {
	Function string
	File     string
	Line     int
}

Frame represents a single stack frame.

Jump to

Keyboard shortcuts

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