errors

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 6 Imported by: 0

README

svcerr

CI

Typed application errors for Go services: error codes, HTTP status mapping, JSON/HTML response writers, panic-recovery middleware, and stack trace capture — with no dependency on any specific logging library.

import "github.com/n-ae/svcerr"

Why

Handlers need to turn an error into the right HTTP status, a safe user-facing message, and a structured log line, without leaking internals (raw SQL, stack traces, third-party error text) into the response. svcerr does that mapping once, centrally, instead of every handler improvising it.

Usage

func (s *Service) GetLeague(id string) (*League, error) {
	var league League
	err := s.db.QueryRow(`SELECT * FROM leagues WHERE id = ?`, id).Scan(&league)
	if err == sql.ErrNoRows {
		return nil, errors.NewNotFoundError("league", id)
	}
	if err != nil {
		return nil, errors.WrapDatabaseError(err, "query", "SELECT * FROM leagues...")
	}
	return &league, nil
}

func (h *Handler) GetLeague(w http.ResponseWriter, r *http.Request) {
	league, err := h.service.GetLeague(r.URL.Query().Get("id"))
	if err != nil {
		// h.logger implements errors.Logger - see "Logging" below
		errors.WriteHTTPError(w, err, h.logger) // maps to the right status, logs, writes JSON
		return
	}
	json.NewEncoder(w).Encode(league)
}

WriteHTTPError writes a JSON body:

{
  "error": {
    "code": "NOT_FOUND",
    "message": "league not found: 12345",
    "details": { "resource_type": "league", "resource_id": "12345" }
  }
}

WriteHTTPErrorHTML writes an HTML fragment instead, for HTMX-style endpoints. UserMessage(err) returns just the sanitized message, for callers embedding it in a custom response.

Check error types with stdlib errors.As — there's no per-type IsXError wrapper:

var nfErr *errors.NotFoundError
if errors.As(err, &nfErr) {
	// ...
}

Recover panics in HTTP handlers and turn them into a proper error response:

router.Use(errors.RecoveryMiddleware(h.logger))
Error types

ValidationError, DatabaseError, ExternalAPIError, AuthenticationError, NotFoundError, ConflictError, RateLimitError, InternalError — each has a New*/Wrap* constructor, carries an ErrorCode, and supports errors.Is/errors.As/errors.Unwrap in the usual way. See the package doc comment in errors.go for the full list of codes and their HTTP status mapping.

Public vs. internal messages

By default the client-facing message is either the error's own Error() text or a generic per-code default — usually fine, but sometimes Error() carries detail (a raw query, an internal hostname) you'd log but not want to send back to a client. SetPublicMessage overrides just the client-facing side for that one error instance; the logged error is untouched:

err := errors.WrapDatabaseError(dbErr, "query", "SELECT * FROM leagues...")
err.SetPublicMessage("We're having trouble reaching the database. Please try again shortly.")
return err // WriteHTTPError/UserMessage now send the override; logs still get err.Error()
Wrapping constructors in your own helper

Every New*/Wrap* constructor assumes it's called directly from the site its stack trace should point at. If you wrap one in your own helper (e.g. a project-wide validation function), the trace ends up pointing at the helper instead of its caller. Fix that with RecaptureStackTrace, called from inside the helper right after construction:

func validateTeamID(id string) error {
	if id == "" {
		err := errors.NewValidationError("team_id is required", "team_id", nil)
		errors.RecaptureStackTrace(err, 1) // point past this helper
		return err
	}
	return nil
}
Logging

WriteHTTPError, WriteHTTPErrorHTML, and RecoveryMiddleware log through a minimal Logger interface, not a specific logging library:

type Logger interface {
	Log(level Level, err error, fields map[string]interface{}, msg string)
}

Using zerolog? Wrap it with the zerologadapter subpackage instead of writing your own adapter:

import "github.com/n-ae/svcerr/zerologadapter"

errors.WriteHTTPError(w, err, zerologadapter.New(logger))

For any other logger, implement the one-method Logger interface directly.

Origin

Extracted from an application's internal/errors package once it had no callers left depending on app-specific behavior — see the release notes for what changed along the way.

Documentation

Overview

Package errors provides custom error types for consistent error handling.

Error types: ValidationError, DatabaseError, ExternalAPIError, AuthenticationError, NotFoundError, ConflictError, RateLimitError, InternalError.

All types implement ErrorWithCode interface and support error wrapping.

The package has no dependency on any specific logging library. WriteHTTPError, WriteHTTPErrorHTML, and RecoveryMiddleware log through the Logger interface - pass an adapter for whatever logger the caller uses (see the zerologadapter subpackage for a zerolog adapter).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetStackTrace

func GetStackTrace(err error) []string

GetStackTrace extracts the stack trace from an error

func HTTPStatusCode

func HTTPStatusCode(code ErrorCode) int

HTTPStatusCode maps error codes to HTTP status codes

func RecaptureStackTrace added in v0.2.1

func RecaptureStackTrace(err error, extraSkip int)

RecaptureStackTrace re-captures err's stack trace starting extraSkip frames higher than the normal New*/Wrap* capture point. Every constructor in this package assumes it's called directly from the site the trace should point at; if you wrap a constructor in your own helper function, the trace ends up pointing at that helper instead of its caller. Call RecaptureStackTrace(err, 1) from inside such a helper, immediately after constructing err, to fix that - err must be one of this package's error types (or wrap one); otherwise this is a no-op.

func RecoveryMiddleware

func RecoveryMiddleware(logger Logger) func(http.Handler) http.Handler

Middleware for error recovery and logging

func UserMessage added in v0.1.1

func UserMessage(err error) string

UserMessage returns the safe, user-facing message for an error - the same sanitized text WriteHTTPError/WriteHTTPErrorHTML send (e.g. a wrapped database error's raw cause is never included), for callers that need to embed it in a custom response fragment instead of one of those two standard bodies.

func WriteHTTPError

func WriteHTTPError(w http.ResponseWriter, err error, logger Logger)

WriteHTTPError writes a standardized error response to the HTTP response writer

func WriteHTTPErrorHTML

func WriteHTTPErrorHTML(w http.ResponseWriter, err error, logger Logger)

WriteHTTPErrorHTML writes an HTML error response (for non-API endpoints)

Types

type AuthenticationError

type AuthenticationError struct {
	BaseError
	SessionID string
	Reason    string // "token_expired", "token_invalid", "permission_denied"
}

AuthenticationError represents authentication and authorization errors

func NewAuthenticationError

func NewAuthenticationError(reason, message string) *AuthenticationError

NewAuthenticationError creates a new authentication error

type BaseError

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

BaseError provides common error functionality

func (*BaseError) Code

func (e *BaseError) Code() ErrorCode

Code returns the error code

func (*BaseError) Context

func (e *BaseError) Context() map[string]interface{}

Context returns the error context

func (*BaseError) Error

func (e *BaseError) Error() string

Error implements the error interface

func (*BaseError) PublicMessage added in v0.2.1

func (e *BaseError) PublicMessage() (string, bool)

PublicMessage returns the message set by SetPublicMessage, and whether one was set at all.

func (*BaseError) SetPublicMessage added in v0.2.1

func (e *BaseError) SetPublicMessage(msg string)

SetPublicMessage overrides the message WriteHTTPError, WriteHTTPErrorHTML, and UserMessage show the client for this error instance, so the logged Error() text (which may carry internal detail) and the client-facing text can differ. Unset by default, in which case those functions fall back to their normal behavior (the error's own message, or a default per-code message).

func (*BaseError) StackTrace

func (e *BaseError) StackTrace() []string

StackTrace returns the captured stack trace

func (*BaseError) Unwrap

func (e *BaseError) Unwrap() error

Unwrap implements error unwrapping

type ConflictError

type ConflictError struct {
	BaseError
	ResourceType string
	ConflictKey  string
}

ConflictError represents resource conflict errors

func NewConflictError

func NewConflictError(resourceType, conflictKey, message string) *ConflictError

NewConflictError creates a new conflict error

type DatabaseError

type DatabaseError struct {
	BaseError
	Operation string // "query", "insert", "update", "delete", "transaction"
	Query     string
}

DatabaseError represents database operation errors

func NewDatabaseError

func NewDatabaseError(operation, message string) *DatabaseError

NewDatabaseError creates a new database error

func WrapDatabaseError

func WrapDatabaseError(err error, operation, query string) *DatabaseError

WrapDatabaseError wraps an existing error as a database error

type ErrorCode

type ErrorCode string

ErrorCode represents application-specific error codes

const (
	// Validation errors (1xxx)
	ErrCodeInvalidInput        ErrorCode = "INVALID_INPUT"
	ErrCodeMissingRequired     ErrorCode = "MISSING_REQUIRED"
	ErrCodeInvalidFormat       ErrorCode = "INVALID_FORMAT"
	ErrCodeConstraintViolation ErrorCode = "CONSTRAINT_VIOLATION"

	// Database errors (2xxx)
	ErrCodeDatabaseConnection  ErrorCode = "DB_CONNECTION"
	ErrCodeDatabaseQuery       ErrorCode = "DB_QUERY"
	ErrCodeDatabaseTransaction ErrorCode = "DB_TRANSACTION"
	ErrCodeDatabaseMigration   ErrorCode = "DB_MIGRATION"

	// External API errors (3xxx). The specific service is carried in
	// ExternalAPIError.Service, not encoded as a separate code per service.
	ErrCodeExternalAPI ErrorCode = "EXTERNAL_API_ERROR"

	// Authentication errors (4xxx)
	ErrCodeUnauthorized     ErrorCode = "UNAUTHORIZED"
	ErrCodeTokenExpired     ErrorCode = "TOKEN_EXPIRED"
	ErrCodeTokenInvalid     ErrorCode = "TOKEN_INVALID"
	ErrCodePermissionDenied ErrorCode = "PERMISSION_DENIED"

	// Resource errors (5xxx)
	ErrCodeNotFound         ErrorCode = "NOT_FOUND"
	ErrCodeAlreadyExists    ErrorCode = "ALREADY_EXISTS"
	ErrCodeResourceConflict ErrorCode = "RESOURCE_CONFLICT"

	// Rate limiting (6xxx)
	ErrCodeRateLimitExceeded ErrorCode = "RATE_LIMIT_EXCEEDED"
	ErrCodeQuotaExceeded     ErrorCode = "QUOTA_EXCEEDED"

	// Internal errors (9xxx). RecoveryMiddleware reports recovered panics
	// as ErrCodeInternal too - there's no separate panic-specific code.
	ErrCodeInternal       ErrorCode = "INTERNAL_ERROR"
	ErrCodeNotImplemented ErrorCode = "NOT_IMPLEMENTED"
)

func GetErrorCode

func GetErrorCode(err error) ErrorCode

GetErrorCode extracts the error code from an error

type ErrorDetail

type ErrorDetail struct {
	Code    ErrorCode              `json:"code"`
	Message string                 `json:"message"`
	Details map[string]interface{} `json:"details,omitempty"`
}

ErrorDetail contains detailed error information for API responses

type ErrorWithCode

type ErrorWithCode interface {
	error
	Code() ErrorCode
	Unwrap() error
	StackTrace() []string
}

ErrorWithCode interface for errors that have application-specific codes

type ExternalAPIError

type ExternalAPIError struct {
	BaseError
	Service    string // caller-defined service name, e.g. "yahoo", "nba_stats"
	StatusCode int
	URL        string
	RetryAfter *int // seconds to retry after; not set by the constructors, assign it directly when known
}

ExternalAPIError represents errors from external APIs

func NewExternalAPIError

func NewExternalAPIError(service, message string, statusCode int, url string) *ExternalAPIError

NewExternalAPIError creates a new external API error

func WrapExternalAPIError

func WrapExternalAPIError(err error, service, url string, statusCode int) *ExternalAPIError

WrapExternalAPIError wraps an existing error as an external API error

type HTTPErrorResponse

type HTTPErrorResponse struct {
	Error ErrorDetail `json:"error"`
}

HTTPErrorResponse represents a standardized HTTP error response

type InternalError

type InternalError struct {
	BaseError
	Component string
}

InternalError represents unexpected internal errors

func NewInternalError

func NewInternalError(component, message string) *InternalError

NewInternalError creates a new internal error

func WrapInternalError

func WrapInternalError(err error, component, message string) *InternalError

WrapInternalError wraps an existing error as an internal error

type Level

type Level int

Level is a log severity, independent of any specific logging library.

const (
	LevelInfo Level = iota
	LevelWarn
	LevelError
)

type Logger

type Logger interface {
	// Log records msg at the given level. err may be nil (e.g. the panic
	// path logs a message with no associated error). fields carries
	// structured context (error_code, http_status, stack_trace, and
	// error-type-specific keys like "field" or "resource_id").
	Log(level Level, err error, fields map[string]interface{}, msg string)
}

Logger is the minimal structured-logging surface this package needs. It has no dependency on any specific logging library - wrap your logger to satisfy it. See the zerologadapter subpackage for a zerolog adapter.

type NotFoundError

type NotFoundError struct {
	BaseError
	ResourceType string
	ResourceID   string
}

NotFoundError represents resource not found errors

func NewNotFoundError

func NewNotFoundError(resourceType, resourceID string) *NotFoundError

NewNotFoundError creates a new not found error

type RateLimitError

type RateLimitError struct {
	BaseError
	Service    string
	Limit      int
	RetryAfter int // seconds
}

RateLimitError represents rate limiting errors

func NewRateLimitError

func NewRateLimitError(service string, limit, retryAfter int) *RateLimitError

NewRateLimitError creates a new rate limit error

type ValidationError

type ValidationError struct {
	BaseError
	Field string
	Value interface{}
}

ValidationError represents input validation errors

func NewValidationError

func NewValidationError(message string, field string, value interface{}) *ValidationError

NewValidationError creates a new validation error

func WrapValidationError

func WrapValidationError(err error, message string, field string) *ValidationError

WrapValidationError wraps an existing error as a validation error

Directories

Path Synopsis
Package zerologadapter adapts a zerolog.Logger to the errors.Logger interface, so the parent package stays free of any logging-library dependency while callers can still log through zerolog.
Package zerologadapter adapts a zerolog.Logger to the errors.Logger interface, so the parent package stays free of any logging-library dependency while callers can still log through zerolog.

Jump to

Keyboard shortcuts

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