xerrors

package
v0.15.1 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 4 Imported by: 1 module, 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.
  • Pre-defined Common Errors: Ready-to-use variables like ErrNotFound, ErrUnauthorized, and ErrInternal.
  • 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/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
}
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. Extracting Context in API Handlers (e.g. Fiber/Gin)

When an error bubbles up to your HTTP handler, you can easily extract the Status Code and String Code to format your JSON response.

func ErrorMiddleware(c *fiber.Ctx, err error) error {
    statusCode := xerrors.HTTPStatusCode(err) // Defaults to 500 if not a CustomError
    stringCode := xerrors.GetCode(err)        // Defaults to "INTERNAL_ERROR"
    
    return c.Status(statusCode).JSON(fiber.Map{
        "code":    stringCode,
        "message": err.Error(),
    })
}
Key Types & Functions
Symbol Description
CustomError The underlying struct implementing the error interface.
New(code, msg, status) Create a new structured error.
Wrap(err, code, msg, status) Wrap an existing error with structured context.
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.

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.

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 added in v0.15.0

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 added in v0.15.0

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 added in v0.15.0

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.

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) StackTrace added in v0.15.0

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 added in v0.15.0

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