Documentation
¶
Overview ¶
Package errors provides domain-specific error types for the Nucleus framework. It defines a DomainError type with HTTP status codes and JSON serialization, along with convenience constructors for common error cases.
The package supports Laravel-style error handling with: - Reportable exceptions (custom logging/reporting) - Renderable exceptions (custom HTTP responses) - Configurable log levels per error type - Global error context - Exception throttling
Index ¶
- Constants
- func WriteError(w http.ResponseWriter, r *http.Request, err error, logger *slog.Logger)
- func WriteProblem(w http.ResponseWriter, r *http.Request, err error)
- type ContextProvider
- type DomainError
- func BadRequest(message string) *DomainError
- func Conflict(message string) *DomainError
- func Forbidden(message string) *DomainError
- func InternalError(message string) *DomainError
- func NotFound(resource, id string) *DomainError
- func Unauthorized(message string) *DomainError
- func ValidationFailed(fields map[string]string) *DomainError
- func (e *DomainError) Context() map[string]any
- func (e *DomainError) Error() string
- func (e *DomainError) LogLevel() slog.Level
- func (e *DomainError) Render(w http.ResponseWriter, r *http.Request) bool
- func (e *DomainError) Report(ctx context.Context, logger *slog.Logger) bool
- func (e *DomainError) WithDetails(details any) *DomainError
- type ErrorBody
- type ErrorHandler
- type ErrorHandlerConfig
- type ErrorResponse
- type LogLevelProvider
- type Problem
- type Renderable
- type Reportable
- type ThrottleConfig
Constants ¶
const ProblemContentType = httpneg.Problem
ProblemContentType is the media type of an RFC 9457 problem details document.
Variables ¶
This section is empty.
Functions ¶
func WriteError ¶
WriteError writes an error as a JSON response using the default handler. This is a convenience function that creates a default handler and uses it. For advanced configuration, use ErrorHandler directly.
func WriteProblem ¶ added in v1.31.0
func WriteProblem(w http.ResponseWriter, r *http.Request, err error)
WriteProblem writes err as a problem details document (see NewProblem), whatever the client's Accept header says; it does not log. The Content-Type is application/problem+json, or application/json for a client that accepts that and not the problem type.
Most code never calls it: a handler returns its error and the router answers in the shape the client and the application chose, and WriteError — the writer middleware uses — makes the same choice.
Types ¶
type ContextProvider ¶
type ContextProvider interface {
// Context returns additional context data for logging.
Context() map[string]any
}
ContextProvider is an interface that errors can implement to provide additional context for logging.
type DomainError ¶
type DomainError struct {
Code string `json:"code"`
Message string `json:"message"`
StatusCode int `json:"-"`
Details any `json:"details,omitempty"`
}
DomainError represents a structured application error with an HTTP status code, a machine-readable code, a human-readable message, and optional details.
func BadRequest ¶
func BadRequest(message string) *DomainError
BadRequest creates a 400 error for malformed or invalid requests.
func Conflict ¶
func Conflict(message string) *DomainError
Conflict creates a 409 error for resource conflicts.
func Forbidden ¶
func Forbidden(message string) *DomainError
Forbidden creates a 403 error for unauthorized access attempts.
func InternalError ¶
func InternalError(message string) *DomainError
InternalError creates a 500 error for unexpected server errors.
func NotFound ¶
func NotFound(resource, id string) *DomainError
NotFound creates a 404 error indicating a resource was not found.
func Unauthorized ¶
func Unauthorized(message string) *DomainError
Unauthorized creates a 401 error for unauthenticated requests.
func ValidationFailed ¶
func ValidationFailed(fields map[string]string) *DomainError
ValidationFailed creates a 422 error with per-field validation details.
func (*DomainError) Context ¶
func (e *DomainError) Context() map[string]any
Context implements ContextProvider for DomainError. Returns the details as context for logging.
func (*DomainError) Error ¶
func (e *DomainError) Error() string
Error implements the error interface.
func (*DomainError) LogLevel ¶
func (e *DomainError) LogLevel() slog.Level
LogLevel implements LogLevelProvider for DomainError. Returns ERROR for 5xx, DEBUG for 4xx.
func (*DomainError) Render ¶
func (e *DomainError) Render(w http.ResponseWriter, r *http.Request) bool
Render implements Renderable for DomainError. By default, DomainErrors use the standard JSON rendering (returns false).
func (*DomainError) Report ¶
Report implements Reportable for DomainError. By default, DomainErrors are not reported (returns false to use default logging).
func (*DomainError) WithDetails ¶
func (e *DomainError) WithDetails(details any) *DomainError
WithDetails returns a copy of the error with the given details attached.
type ErrorBody ¶
type ErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
}
ErrorBody holds the structured error fields.
type ErrorHandler ¶
type ErrorHandler struct {
// contains filtered or unexported fields
}
ErrorHandler handles error reporting and rendering with Laravel-style separation.
func NewErrorHandler ¶
func NewErrorHandler(logger *slog.Logger, config *ErrorHandlerConfig) *ErrorHandler
NewErrorHandler creates a new ErrorHandler with the given configuration.
func (*ErrorHandler) Render ¶
func (h *ErrorHandler) Render(w http.ResponseWriter, r *http.Request, err error)
Render handles error rendering to HTTP response. It respects Renderable interface.
type ErrorHandlerConfig ¶
type ErrorHandlerConfig struct {
// GlobalContext is a function that returns context data to include in all error logs.
GlobalContext func(ctx context.Context) map[string]any
// LogLevelMap allows configuring log levels for specific error types.
LogLevelMap map[error]slog.Level
// IgnoredErrors are error types that should not be reported (logged).
IgnoredErrors []error
// ThrottleConfig configures throttling of error reporting.
ThrottleConfig *ThrottleConfig
}
ErrorHandlerConfig configures the error handler behavior.
type ErrorResponse ¶
type ErrorResponse struct {
Error ErrorBody `json:"error"`
}
ErrorResponse is the JSON envelope returned for all errors.
type LogLevelProvider ¶
type LogLevelProvider interface {
// LogLevel returns the log level for this error.
LogLevel() slog.Level
}
LogLevelProvider is an interface that errors can implement to specify their log level.
type Problem ¶ added in v1.31.0
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Code string `json:"code,omitempty"`
Details any `json:"details,omitempty"`
}
Problem is an error as an RFC 9457 problem details document — the second error shape, beside the envelope {"error": {"code", "message", "details"}} (ErrorResponse) every error has answered in since v0.
A client gets it when it asks for it — an Accept header that prefers application/problem+json to application/json — or for every error when the application opted in (app.WithProblemDetails, the builder's WithProblemDetails, or router.WithProblemDetails on a bare router). Otherwise the envelope answers, unchanged; it stays the default until the next major.
The standard members carry the HTTP view of the error: Type is "about:blank" (RFC 9457 §4.2.1: the status code says all there is), Title the status phrase, Status the code, Detail the error's message and Instance the request path. Two extension members carry what the envelope carries and the standard members cannot: Code, the framework's machine-readable code ("NOT_FOUND", "VALIDATION_FAILED", …), and Details, the error's details — for a validation failure, the message per field.
func NewProblem ¶ added in v1.31.0
NewProblem builds the problem details document for err answered to r. A *DomainError anywhere in err's chain gives its status, code, message and details; any other error is a 500 whose detail is the generic message the envelope uses, never err.Error(). r may be nil (no Instance).
type Renderable ¶
type Renderable interface {
// Render returns a custom HTTP response. Return false to fall back to default rendering.
Render(w http.ResponseWriter, r *http.Request) bool
}
Renderable is an interface that errors can implement to provide custom HTTP rendering logic.
type Reportable ¶
type Reportable interface {
// Report handles the error reporting. Return false to fall back to default logging.
Report(ctx context.Context, logger *slog.Logger) bool
}
Reportable is an interface that errors can implement to provide custom reporting logic (e.g., sending to Sentry, Flare, or other external services).
type ThrottleConfig ¶
type ThrottleConfig struct {
// SampleRate is the fraction of errors to log (0.0 to 1.0).
// 0.1 means log 10% of errors.
SampleRate float64
// RateLimit is the maximum number of errors to log per duration.
RateLimit int
Duration time.Duration
// KeyFunc determines the throttling key for an error.
// If nil, uses error type as key.
KeyFunc func(error) string
}
ThrottleConfig configures throttling of error reporting.