errors

package
v0.1.36 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

errors/errors.go

errors/http.go

Index

Constants

View Source
const (
	CodeBadRequest           = "bad_request"
	CodeUnauthorized         = "unauthorized"
	CodeForbidden            = "forbidden"
	CodeNotFound             = "not_found"
	CodeMethodNotAllowed     = "method_not_allowed"
	CodeConflict             = "conflict"
	CodeGone                 = "gone"
	CodeUnprocessableEntity  = "unprocessable_entity"
	CodeTooManyRequests      = "too_many_requests"
	CodeInternalError        = "internal_error"
	CodeNotImplemented       = "not_implemented"
	CodeServiceUnavailable   = "service_unavailable"
	CodeTimeout              = "timeout"
	CodeValidationFailed     = "validation_failed"
	CodeAlreadyExists        = "already_exists"
	CodeInvalidInput         = "invalid_input"
	CodeAuthenticationFailed = "authentication_failed"
	CodePermissionDenied     = "permission_denied"
)

Common error codes as constants for consistency.

Variables

This section is empty.

Functions

func As

func As(err error, target any) bool

As finds the first error in err's chain that matches target. Re-exported from standard errors package for convenience.

func CodeFromError

func CodeFromError(err error) string

CodeFromError returns the error code for an error. Returns "internal_error" if the error is not an *Error.

func Handler

func Handler(h http.Handler, logger *zap.Logger) http.Handler

Handler wraps an http.Handler and recovers from panics, writing an error response.

func HandlerFunc

func HandlerFunc(h http.HandlerFunc, logger *zap.Logger) http.HandlerFunc

HandlerFunc is like Handler but for http.HandlerFunc.

func Is

func Is(err, target error) bool

Is reports whether any error in err's chain matches target. Re-exported from standard errors package for convenience.

func Join

func Join(errs ...error) error

Join returns an error that wraps the given errors. Re-exported from standard errors package for convenience.

func MethodNotAllowedHandler

func MethodNotAllowedHandler() http.Handler

MethodNotAllowedHandler returns an http.Handler that responds with 405 Method Not Allowed.

func Middleware

func Middleware(logger *zap.Logger) func(http.Handler) http.Handler

Middleware returns middleware that handles errors returned from handlers. Use with ErrorHandlerFunc-style handlers via context.

func NotFoundHandler

func NotFoundHandler() http.Handler

NotFoundHandler returns an http.Handler that responds with 404 Not Found.

func StatusFromError

func StatusFromError(err error) int

StatusFromError returns the HTTP status code for an error. Returns 500 if the error is not an *Error.

func WrapHandler

func WrapHandler(h ErrorHandlerFunc) http.HandlerFunc

WrapHandler converts an ErrorHandlerFunc to a standard http.HandlerFunc.

func WrapWithLogger

func WrapWithLogger(h ErrorHandlerFunc, logger *zap.Logger) http.HandlerFunc

WrapWithLogger converts an ErrorHandlerFunc to a standard http.HandlerFunc, logging internal errors.

func Write

func Write(w http.ResponseWriter, err error)

Write writes an error as JSON to the response. It sets the appropriate HTTP status code and Content-Type header.

func WriteWithLogger

func WriteWithLogger(w http.ResponseWriter, err error, logger *zap.Logger)

WriteWithLogger writes an error and logs internal errors.

Types

type Error

type Error struct {
	// Code is a machine-readable error code (e.g., "not_found", "validation_failed")
	Code string `json:"code"`

	// Message is a human-readable error message
	Message string `json:"message"`

	// Status is the HTTP status code (not included in JSON by default)
	Status int `json:"-"`

	// Details contains additional error context (optional)
	Details map[string]any `json:"details,omitempty"`

	// Err is the underlying error (not included in JSON)
	Err error `json:"-"`
}

Error represents a structured application error with code, message, and HTTP status.

func AlreadyExists

func AlreadyExists(message string) *Error

AlreadyExists creates a 409 Conflict error with already_exists code.

func AuthenticationFailed

func AuthenticationFailed(message string) *Error

AuthenticationFailed creates a 401 Unauthorized error with authentication_failed code.

func BadRequest

func BadRequest(message string) *Error

BadRequest creates a 400 Bad Request error.

func Conflict

func Conflict(message string) *Error

Conflict creates a 409 Conflict error.

func Forbidden

func Forbidden(message string) *Error

Forbidden creates a 403 Forbidden error.

func From

func From(err error) *Error

From extracts an *Error from err if possible, or wraps it as an internal error.

func Gone

func Gone(message string) *Error

Gone creates a 410 Gone error.

func Internal

func Internal(message string) *Error

Internal creates a 500 Internal Server Error.

func InvalidInput

func InvalidInput(message string) *Error

InvalidInput creates a 400 Bad Request error with invalid_input code.

func MethodNotAllowed

func MethodNotAllowed(message string) *Error

MethodNotAllowed creates a 405 Method Not Allowed error.

func New

func New(code, message string, status int) *Error

New creates a new Error with code, message, and HTTP status.

func NotFound

func NotFound(message string) *Error

NotFound creates a 404 Not Found error.

func NotImplemented

func NotImplemented(message string) *Error

NotImplemented creates a 501 Not Implemented error.

func PermissionDenied

func PermissionDenied(message string) *Error

PermissionDenied creates a 403 Forbidden error with permission_denied code.

func ServiceUnavailable

func ServiceUnavailable(message string) *Error

ServiceUnavailable creates a 503 Service Unavailable error.

func Timeout

func Timeout(message string) *Error

Timeout creates a 504 Gateway Timeout error.

func TooManyRequests

func TooManyRequests(message string) *Error

TooManyRequests creates a 429 Too Many Requests error.

func Unauthorized

func Unauthorized(message string) *Error

Unauthorized creates a 401 Unauthorized error.

func UnprocessableEntity

func UnprocessableEntity(message string) *Error

UnprocessableEntity creates a 422 Unprocessable Entity error.

func Validation

func Validation(message string) *Error

Validation creates a 400 Bad Request error with validation code.

func Wrap

func Wrap(err error, code, message string, status int) *Error

Wrap creates a new Error wrapping an existing error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) HTTPStatus

func (e *Error) HTTPStatus() int

HTTPStatus returns the HTTP status code for the error.

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error for errors.Is/As support.

func (*Error) WithDetail

func (e *Error) WithDetail(key string, value any) *Error

WithDetail adds a single detail to the error.

func (*Error) WithDetails

func (e *Error) WithDetails(details map[string]any) *Error

WithDetails adds details to the error.

func (*Error) Wrap

func (e *Error) Wrap(err error) *Error

Wrap wraps an underlying error.

type ErrorHandlerFunc

type ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request) error

ErrorHandlerFunc is a handler function that returns an error. If the error is non-nil, it is written as JSON.

type FieldError

type FieldError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
	Code    string `json:"code,omitempty"`
}

FieldError represents a validation error on a specific field.

type Response

type Response struct {
	Error *Error `json:"error"`
}

Response is the JSON structure returned for errors.

type ValidationErrors

type ValidationErrors struct {
	Errors []FieldError `json:"errors"`
}

ValidationErrors holds multiple field-level validation errors.

func NewValidationErrors

func NewValidationErrors() *ValidationErrors

NewValidationErrors creates a new ValidationErrors.

func (*ValidationErrors) Add

func (v *ValidationErrors) Add(field, message string) *ValidationErrors

Add adds a field error.

func (*ValidationErrors) AddWithCode

func (v *ValidationErrors) AddWithCode(field, message, code string) *ValidationErrors

AddWithCode adds a field error with a code.

func (*ValidationErrors) Error

func (v *ValidationErrors) Error() string

Error implements the error interface.

func (*ValidationErrors) HasErrors

func (v *ValidationErrors) HasErrors() bool

HasErrors returns true if there are validation errors.

func (*ValidationErrors) ToError

func (v *ValidationErrors) ToError() *Error

ToError converts ValidationErrors to an *Error if there are errors.

Jump to

Keyboard shortcuts

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