exceptions

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package exceptions provides Laravel-style exception handling for Velocity. It includes rich error pages in development and safe error responses in production.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrorHandler

func ErrorHandler(handler *Handler) func(http.ResponseWriter, *http.Request, error)

ErrorHandler creates an error handler function for use with routers that support error returns.

func Handle

func Handle(ctx RenderContext, err error)

Handle handles an exception using the global handler.

func HandleWithContext

func HandleWithContext(ctx RenderContext, err error, exCtx *ExceptionContext)

HandleWithContext handles an exception with context using the global handler.

func Initialize

func Initialize(opts ...HandlerOption)

Initialize initializes the global exception handler. This is called automatically on first use, but can be called explicitly to configure the handler before use.

func IsAPIMode

func IsAPIMode() bool

IsAPIMode returns whether API mode is enabled on the global handler.

func IsDebug

func IsDebug() bool

IsDebug returns whether the global handler is in debug mode.

func Middleware

func Middleware(handler *Handler) func(http.Handler) http.Handler

Middleware creates an HTTP middleware that handles exceptions and panics.

func MiddlewareFunc

func MiddlewareFunc(handler *Handler) func(http.HandlerFunc) http.HandlerFunc

MiddlewareFunc creates an HTTP middleware function.

func RecoverMiddleware

func RecoverMiddleware(next http.Handler) http.Handler

RecoverMiddleware is a simple panic recovery middleware that uses the global handler.

func Render

func Render(ctx RenderContext, err error, exCtx *ExceptionContext)

Render renders an exception using the global handler.

func Report

func Report(err error, ctx *ExceptionContext)

Report reports an exception using the global handler.

func ResetGlobal

func ResetGlobal()

ResetGlobal resets the global handler for testing purposes. This should only be used in tests.

func SetAPIMode

func SetAPIMode(enabled bool)

SetAPIMode sets the API mode on the global handler.

func SetAPIPrefixes

func SetAPIPrefixes(prefixes ...string)

SetAPIPrefixes sets URL prefixes that indicate API routes on the global handler.

func SetDebug

func SetDebug(debug bool)

SetDebug sets the debug mode on the global handler.

func SetGlobal

func SetGlobal(handler *Handler)

SetGlobal sets the global exception handler. This can be used to replace the default handler with a custom one.

Types

type BadRequestHttpException

type BadRequestHttpException struct {
	*HttpException
}

BadRequestHttpException represents a 400 Bad Request error.

func NewBadRequestHttpException

func NewBadRequestHttpException(message ...string) *BadRequestHttpException

NewBadRequestHttpException creates a new 400 exception.

func (*BadRequestHttpException) ShouldReport

func (e *BadRequestHttpException) ShouldReport() bool

ShouldReport returns false - bad request errors shouldn't be logged.

type BaseException

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

BaseException provides a base implementation of the Exception interface.

func NewBaseException

func NewBaseException(message string, code int) *BaseException

NewBaseException creates a new BaseException.

func (*BaseException) Error

func (e *BaseException) Error() string

Error implements the error interface.

func (*BaseException) GetCode

func (e *BaseException) GetCode() int

GetCode returns the exception code.

func (*BaseException) GetContext

func (e *BaseException) GetContext() map[string]any

GetContext returns the exception context.

func (*BaseException) GetMessage

func (e *BaseException) GetMessage() string

GetMessage returns the exception message.

func (*BaseException) GetPrevious

func (e *BaseException) GetPrevious() error

GetPrevious returns the previous/wrapped error.

func (*BaseException) ShouldReport

func (e *BaseException) ShouldReport() bool

ShouldReport returns true by default - exceptions should be reported.

func (*BaseException) Unwrap

func (e *BaseException) Unwrap() error

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

func (*BaseException) WithContext

func (e *BaseException) WithContext(key string, value any) *BaseException

WithContext adds context data and returns the exception for chaining.

func (*BaseException) WithContextMap

func (e *BaseException) WithContextMap(ctx map[string]any) *BaseException

WithContextMap merges a map into the exception context.

func (*BaseException) WithPrevious

func (e *BaseException) WithPrevious(err error) *BaseException

WithPrevious sets the previous error and returns the exception for chaining.

type CallbackReporter

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

CallbackReporter reports exceptions using a callback function.

func NewCallbackReporter

func NewCallbackReporter(callback func(err error, ctx *ExceptionContext)) *CallbackReporter

NewCallbackReporter creates a new CallbackReporter.

func (*CallbackReporter) Report

func (r *CallbackReporter) Report(err error, ctx *ExceptionContext)

Report calls the callback function with the error and context.

type ConflictHttpException

type ConflictHttpException struct {
	*HttpException
}

ConflictHttpException represents a 409 Conflict error.

func NewConflictHttpException

func NewConflictHttpException(message ...string) *ConflictHttpException

NewConflictHttpException creates a new 409 exception.

func (*ConflictHttpException) ShouldReport

func (e *ConflictHttpException) ShouldReport() bool

ShouldReport returns false - conflict errors typically shouldn't be logged.

type Exception

type Exception interface {
	error
	GetMessage() string
	GetCode() int
	GetPrevious() error
	GetContext() map[string]any
}

Exception is the base interface for all exceptions.

type ExceptionContext

type ExceptionContext struct {
	RequestID  string
	TraceID    string
	UserID     string
	URL        string
	Method     string
	IP         string
	UserAgent  string
	Timestamp  time.Time
	StackTrace *StackTrace
	Extra      map[string]any
}

ExceptionContext contains contextual information about where an exception occurred.

func NewExceptionContext

func NewExceptionContext() *ExceptionContext

NewExceptionContext creates a new ExceptionContext with the current timestamp.

func (*ExceptionContext) WithExtra

func (c *ExceptionContext) WithExtra(key string, value any) *ExceptionContext

WithExtra adds extra data to the context.

func (*ExceptionContext) WithIDs

func (c *ExceptionContext) WithIDs(requestID, traceID string) *ExceptionContext

WithIDs adds request and trace IDs to the context.

func (*ExceptionContext) WithRequestInfo

func (c *ExceptionContext) WithRequestInfo(method, url, ip, userAgent string) *ExceptionContext

WithRequestInfo adds request information to the context.

func (*ExceptionContext) WithStackTrace

func (c *ExceptionContext) WithStackTrace(st *StackTrace) *ExceptionContext

WithStackTrace adds a stack trace to the context.

func (*ExceptionContext) WithUserID

func (c *ExceptionContext) WithUserID(userID string) *ExceptionContext

WithUserID adds user ID to the context.

type ForbiddenHttpException

type ForbiddenHttpException struct {
	*HttpException
}

ForbiddenHttpException represents a 403 Forbidden error.

func NewForbiddenHttpException

func NewForbiddenHttpException(message ...string) *ForbiddenHttpException

NewForbiddenHttpException creates a new 403 exception.

func (*ForbiddenHttpException) ShouldReport

func (e *ForbiddenHttpException) ShouldReport() bool

ShouldReport returns false - forbidden errors typically shouldn't be logged as errors.

type Frame

type Frame struct {
	File     string
	Line     int
	Function string
	Package  string
}

Frame represents a single stack frame.

func (*Frame) ShortFile

func (f *Frame) ShortFile() string

ShortFile returns a shortened version of the file path.

type FrameWithSource

type FrameWithSource struct {
	Frame
	Source    []SourceLine
	SourceErr error
}

FrameWithSource represents a stack frame with its source context.

type GoneHttpException

type GoneHttpException struct {
	*HttpException
}

GoneHttpException represents a 410 Gone error.

func NewGoneHttpException

func NewGoneHttpException(message ...string) *GoneHttpException

NewGoneHttpException creates a new 410 exception.

func (*GoneHttpException) ShouldReport

func (e *GoneHttpException) ShouldReport() bool

ShouldReport returns false - gone errors shouldn't be logged.

type HTMLRenderer

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

HTMLRenderer renders exceptions as HTML.

func NewHTMLRenderer

func NewHTMLRenderer() *HTMLRenderer

NewHTMLRenderer creates a new HTMLRenderer with the embedded templates.

func NewHTMLRendererWithTemplates

func NewHTMLRendererWithTemplates(debugTpl, errorTpl *template.Template) *HTMLRenderer

NewHTMLRendererWithTemplates creates a new HTMLRenderer with custom templates.

func (*HTMLRenderer) ContentType

func (r *HTMLRenderer) ContentType() string

ContentType returns the HTML content type.

func (*HTMLRenderer) Render

func (r *HTMLRenderer) Render(ctx RenderContext, err error, exCtx *ExceptionContext, debug bool) error

Render renders the exception as HTML.

type Handler

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

Handler is the main exception handler.

func Get

func Get() *Handler

Get returns the global exception handler. If not initialized, it will be initialized with default settings.

func NewHandler

func NewHandler(opts ...HandlerOption) *Handler

NewHandler creates a new exception handler.

func (*Handler) AddRenderer

func (h *Handler) AddRenderer(contentType string, renderer Renderer)

AddRenderer adds a renderer for a content type.

func (*Handler) AddReporter

func (h *Handler) AddReporter(reporter Reporter)

AddReporter adds a reporter to the handler.

func (*Handler) DontReport

func (h *Handler) DontReport(exceptionType string)

DontReport adds an exception type to the don't report list.

func (*Handler) GetAPIPrefixes

func (h *Handler) GetAPIPrefixes() []string

GetAPIPrefixes returns the configured API prefixes.

func (*Handler) GetEnvironment

func (h *Handler) GetEnvironment() string

GetEnvironment returns the current environment.

func (*Handler) Handle

func (h *Handler) Handle(ctx RenderContext, err error)

Handle is a convenience method that reports and renders an exception.

func (*Handler) HandlePanic

func (h *Handler) HandlePanic(ctx RenderContext, recovered any)

HandlePanic handles a recovered panic value.

func (*Handler) HandleWithContext

func (h *Handler) HandleWithContext(ctx RenderContext, err error, exCtx *ExceptionContext)

HandleWithContext reports and renders with a provided context.

func (*Handler) IsAPIMode

func (h *Handler) IsAPIMode() bool

IsAPIMode returns whether API mode is enabled.

func (*Handler) IsDebug

func (h *Handler) IsDebug() bool

IsDebug returns whether debug mode is enabled.

func (*Handler) RegisterCustomHandler

func (h *Handler) RegisterCustomHandler(exceptionType any, handler func(RenderContext, error, *ExceptionContext))

RegisterCustomHandler registers a custom handler for a specific exception type.

func (*Handler) Render

func (h *Handler) Render(ctx RenderContext, err error, exCtx *ExceptionContext)

Render renders an exception response.

func (*Handler) Report

func (h *Handler) Report(err error, ctx *ExceptionContext)

Report reports an exception to all configured reporters.

func (*Handler) SetAPIMode

func (h *Handler) SetAPIMode(enabled bool)

SetAPIMode enables or disables API mode.

func (*Handler) SetAPIPrefixes

func (h *Handler) SetAPIPrefixes(prefixes ...string)

SetAPIPrefixes sets URL prefixes that indicate API routes.

func (*Handler) SetDebug

func (h *Handler) SetDebug(debug bool)

SetDebug sets the debug mode.

func (*Handler) SetEnvironment

func (h *Handler) SetEnvironment(env string)

SetEnvironment sets the environment.

func (*Handler) SetReporters

func (h *Handler) SetReporters(reporters ...Reporter)

SetReporters replaces all reporters.

func (*Handler) ShouldReport

func (h *Handler) ShouldReport(err error) bool

ShouldReport determines if an exception should be reported.

type HandlerOption

type HandlerOption func(*Handler)

HandlerOption is a functional option for configuring the Handler.

func WithAPIMode

func WithAPIMode(enabled bool) HandlerOption

WithAPIMode enables API mode where all responses are JSON.

func WithAPIPrefixes

func WithAPIPrefixes(prefixes ...string) HandlerOption

WithAPIPrefixes sets URL prefixes that indicate API routes. Requests to these paths will always receive JSON responses.

func WithDebug

func WithDebug(debug bool) HandlerOption

WithDebug enables or disables debug mode.

func WithDontReport

func WithDontReport(types ...string) HandlerOption

WithDontReport sets exception types that should not be reported.

func WithEnvironment

func WithEnvironment(env string) HandlerOption

WithEnvironment sets the environment name.

func WithRenderers

func WithRenderers(renderers map[string]Renderer) HandlerOption

WithRenderers sets the renderers.

func WithReporters

func WithReporters(reporters ...Reporter) HandlerOption

WithReporters sets the reporters.

type HttpException

type HttpException struct {
	*BaseException
	StatusCode int
	Headers    map[string]string
}

HttpException represents an HTTP-specific exception with a status code.

func Abort

func Abort(statusCode int, message ...string) *HttpException

Abort creates an HttpException with the given status code.

func AbortIf

func AbortIf(condition bool, statusCode int, message ...string) *HttpException

AbortIf creates an HttpException if the condition is true.

func AbortUnless

func AbortUnless(condition bool, statusCode int, message ...string) *HttpException

AbortUnless creates an HttpException if the condition is false.

func NewHttpException

func NewHttpException(statusCode int, message string) *HttpException

NewHttpException creates a new HttpException.

func (*HttpException) GetHeaders

func (e *HttpException) GetHeaders() map[string]string

GetHeaders returns the response headers.

func (*HttpException) GetStatusCode

func (e *HttpException) GetStatusCode() int

GetStatusCode returns the HTTP status code.

func (*HttpException) ShouldReport

func (e *HttpException) ShouldReport() bool

ShouldReport returns false for client errors (4xx), true for server errors (5xx).

func (*HttpException) WithHeader

func (e *HttpException) WithHeader(key, value string) *HttpException

WithHeader adds a header to the response.

func (*HttpException) WithHeaders

func (e *HttpException) WithHeaders(headers map[string]string) *HttpException

WithHeaders adds multiple headers to the response.

type InternalServerErrorException

type InternalServerErrorException struct {
	*HttpException
}

InternalServerErrorException represents a 500 Internal Server Error.

func NewInternalServerErrorException

func NewInternalServerErrorException(message ...string) *InternalServerErrorException

NewInternalServerErrorException creates a new 500 exception.

type JSONRenderer

type JSONRenderer struct{}

JSONRenderer renders exceptions as JSON.

func NewJSONRenderer

func NewJSONRenderer() *JSONRenderer

NewJSONRenderer creates a new JSONRenderer.

func (*JSONRenderer) ContentType

func (r *JSONRenderer) ContentType() string

ContentType returns the JSON content type.

func (*JSONRenderer) Render

func (r *JSONRenderer) Render(ctx RenderContext, err error, exCtx *ExceptionContext, debug bool) error

Render renders the exception as JSON.

type LogReporter

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

LogReporter reports exceptions to the log package.

func NewLogReporter

func NewLogReporter(opts ...LogReporterOption) *LogReporter

NewLogReporter creates a new LogReporter.

func (*LogReporter) Report

func (r *LogReporter) Report(err error, ctx *ExceptionContext)

Report logs an exception with its context.

type LogReporterOption

type LogReporterOption func(*LogReporter)

LogReporterOption is a functional option for LogReporter.

func WithContextKeys

func WithContextKeys(keys ...string) LogReporterOption

WithContextKeys sets which context keys to include in logs.

func WithLogger

func WithLogger(logger log.Logger) LogReporterOption

WithLogger sets a custom logger for the reporter.

func WithoutContext

func WithoutContext() LogReporterOption

WithoutContext disables context inclusion in logs.

type MethodNotAllowedHttpException

type MethodNotAllowedHttpException struct {
	*HttpException
	AllowedMethods []string
}

MethodNotAllowedHttpException represents a 405 Method Not Allowed error.

func NewMethodNotAllowedHttpException

func NewMethodNotAllowedHttpException(allowedMethods []string, message ...string) *MethodNotAllowedHttpException

NewMethodNotAllowedHttpException creates a new 405 exception.

func (*MethodNotAllowedHttpException) ShouldReport

func (e *MethodNotAllowedHttpException) ShouldReport() bool

ShouldReport returns false - method not allowed errors shouldn't be logged.

type MultiReporter

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

MultiReporter reports to multiple reporters.

func NewMultiReporter

func NewMultiReporter(reporters ...Reporter) *MultiReporter

NewMultiReporter creates a new MultiReporter.

func (*MultiReporter) AddReporter

func (r *MultiReporter) AddReporter(reporter Reporter)

AddReporter adds a reporter to the multi-reporter.

func (*MultiReporter) Report

func (r *MultiReporter) Report(err error, ctx *ExceptionContext)

Report sends the error to all reporters.

type NotFoundHttpException

type NotFoundHttpException struct {
	*HttpException
}

NotFoundHttpException represents a 404 Not Found error.

func NewNotFoundHttpException

func NewNotFoundHttpException(message ...string) *NotFoundHttpException

NewNotFoundHttpException creates a new 404 exception.

func (*NotFoundHttpException) ShouldReport

func (e *NotFoundHttpException) ShouldReport() bool

ShouldReport returns false - 404s typically shouldn't be logged as errors.

type RenderContext

type RenderContext interface {
	WriteHeader(statusCode int)
	Write(data []byte) (int, error)
	SetHeader(key, value string)
	GetHeader(key string) string
	RequestPath() string
	RequestMethod() string
	WantsJSON() bool
}

RenderContext provides the context needed for rendering exceptions.

type Renderable

type Renderable interface {
	Render(ctx RenderContext) error
}

Renderable indicates an exception can render its own response.

type Renderer

type Renderer interface {
	Render(ctx RenderContext, err error, exCtx *ExceptionContext, debug bool) error
	ContentType() string
}

Renderer is the interface for exception renderers.

func NegotiateRenderer

func NegotiateRenderer(ctx RenderContext, renderers map[string]Renderer) Renderer

NegotiateRenderer selects the appropriate renderer based on content negotiation.

type Reportable

type Reportable interface {
	ShouldReport() bool
}

Reportable indicates if an exception should be logged.

type Reporter

type Reporter interface {
	Report(err error, ctx *ExceptionContext)
}

Reporter is the interface for exception reporters.

type ServiceUnavailableException

type ServiceUnavailableException struct {
	*HttpException
	RetryAfter int // Seconds until service might be available
}

ServiceUnavailableException represents a 503 Service Unavailable error.

func NewServiceUnavailableException

func NewServiceUnavailableException(retryAfter int, message ...string) *ServiceUnavailableException

NewServiceUnavailableException creates a new 503 exception.

type SourceLine

type SourceLine struct {
	Number    int
	Content   string
	Highlight bool
}

SourceLine represents a line of source code.

func GetSourceContext

func GetSourceContext(file string, line int, contextLines int) ([]SourceLine, error)

GetSourceContext retrieves source code lines around a specific line in a file. It returns contextLines lines before and after the target line.

type StackTrace

type StackTrace struct {
	Frames []Frame
}

StackTrace represents a captured stack trace.

func CaptureStackTrace

func CaptureStackTrace(skip int) *StackTrace

CaptureStackTrace captures the current stack trace, skipping the specified number of frames.

func (*StackTrace) GetFramesWithSource

func (st *StackTrace) GetFramesWithSource(contextLines int) []FrameWithSource

GetFramesWithSource returns stack frames with source code context.

func (*StackTrace) String

func (st *StackTrace) String() string

String returns a formatted string representation of the stack trace.

type TooManyRequestsException

type TooManyRequestsException struct {
	*HttpException
	RetryAfter int // Seconds until retry is allowed
}

TooManyRequestsException represents a 429 Too Many Requests error.

func NewTooManyRequestsException

func NewTooManyRequestsException(retryAfter int, message ...string) *TooManyRequestsException

NewTooManyRequestsException creates a new 429 exception.

func (*TooManyRequestsException) ShouldReport

func (e *TooManyRequestsException) ShouldReport() bool

ShouldReport returns false - rate limiting shouldn't be logged as errors.

type UnauthorizedHttpException

type UnauthorizedHttpException struct {
	*HttpException
}

UnauthorizedHttpException represents a 401 Unauthorized error.

func NewUnauthorizedHttpException

func NewUnauthorizedHttpException(message ...string) *UnauthorizedHttpException

NewUnauthorizedHttpException creates a new 401 exception.

func (*UnauthorizedHttpException) ShouldReport

func (e *UnauthorizedHttpException) ShouldReport() bool

ShouldReport returns false - auth failures typically shouldn't be logged as errors.

type ValidationException

type ValidationException struct {
	*HttpException
	ValidationErrors map[string][]string
}

ValidationException represents a 422 Unprocessable Entity error with validation errors.

func NewValidationException

func NewValidationException(errors map[string][]string, message ...string) *ValidationException

NewValidationException creates a new validation exception.

func (*ValidationException) GetValidationErrors

func (e *ValidationException) GetValidationErrors() map[string][]string

GetValidationErrors returns the validation errors.

func (*ValidationException) Render

func (e *ValidationException) Render(ctx RenderContext) error

Render implements Renderable for custom JSON response.

func (*ValidationException) ShouldReport

func (e *ValidationException) ShouldReport() bool

ShouldReport returns false - validation errors shouldn't be logged.

type VelocityContextAdapter

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

VelocityContextAdapter adapts a velocity router context to RenderContext. This is a generic implementation that can work with any context type that has the required methods.

func NewVelocityContextAdapter

func NewVelocityContextAdapter(w http.ResponseWriter, r *http.Request) *VelocityContextAdapter

NewVelocityContextAdapter creates a new adapter from response writer and request.

func (*VelocityContextAdapter) GetHeader

func (a *VelocityContextAdapter) GetHeader(key string) string

GetHeader gets a request header.

func (*VelocityContextAdapter) RequestMethod

func (a *VelocityContextAdapter) RequestMethod() string

RequestMethod returns the request method.

func (*VelocityContextAdapter) RequestPath

func (a *VelocityContextAdapter) RequestPath() string

RequestPath returns the request path.

func (*VelocityContextAdapter) SetHeader

func (a *VelocityContextAdapter) SetHeader(key, value string)

SetHeader sets a response header.

func (*VelocityContextAdapter) WantsJSON

func (a *VelocityContextAdapter) WantsJSON() bool

WantsJSON returns true if the request prefers JSON response.

func (*VelocityContextAdapter) Write

func (a *VelocityContextAdapter) Write(data []byte) (int, error)

Write writes data to the response.

func (*VelocityContextAdapter) WriteHeader

func (a *VelocityContextAdapter) WriteHeader(statusCode int)

WriteHeader writes the HTTP status code.

Jump to

Keyboard shortcuts

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