errors

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearReporters

func ClearReporters()

ClearReporters removes all registered reporters (useful in tests).

func Handler

func Handler() router.Middleware

Handler is a global error handler. When a handler returns an error, this middleware catches it. Behavior:

  • validation.ValidationErrors → 422 JSON
  • *AppError → tracked error with ID, reported to registered reporters
  • HTTPError → status from error
  • fallback → 500 JSON with error ID for tracking

func NotFoundHandler

func NotFoundHandler() func(*http.Context) error

NotFoundHandler returns a router handler for unmatched routes (use with app.Router.Fallback). It is registered automatically by nimbus.New().

func RegisterExceptionRecorder

func RegisterExceptionRecorder(fn func(class, message, file string, line int, trace string))

RegisterExceptionRecorder registers a callback invoked when the global error handler records an exception (AppError, unhandled handler error, or panic). Used by the Telescope plugin; safe to call with nil to clear.

func RegisterReporter

func RegisterReporter(r Reporter)

RegisterReporter adds an error reporter. When errors are handled by the error handler middleware, they are also sent to all registered reporters.

errors.RegisterReporter(&SentryReporter{DSN: "https://..."})

func RelPath

func RelPath(path string) string

RelPath returns a path relative to the working directory.

func RenderDefaultHTML

func RenderDefaultHTML(c *http.Context, data HTMLPageData) error

RenderDefaultHTML writes the built-in HTML error page.

func ReportError

func ReportError(err error, context map[string]any)

ReportError sends an error to all registered reporters.

func SmartErrorHandler

func SmartErrorHandler(cfg ...DevPageConfig) router.Middleware

SmartErrorHandler returns middleware that renders rich HTML error pages in development mode, with source code context and diagnostic hints.

func WantsHTML

func WantsHTML(c *http.Context) bool

WantsHTML reports whether the client prefers an HTML error response. Browsers typically send Accept: text/html; XHR/API clients often send Accept: application/json or X-Requested-With: XMLHttpRequest.

func WriteHTTPError

func WriteHTTPError(c *http.Context, he HTTPError)

WriteHTTPError renders an HTTPError to the response. It is used by both the errors.Handler middleware and the router's fallback when no global handler is installed.

Types

type AppError

type AppError struct {
	ID        string    `json:"error_id"`
	Status    int       `json:"status"`
	Message   string    `json:"message"`
	Internal  error     `json:"-"` // original error, not exposed to client
	Timestamp time.Time `json:"timestamp"`
	// StackTrace is set for panics (middleware.Recover) for Telescope / logs.
	StackTrace string `json:"-"`
}

AppError is an application error with a unique ID for tracking. When returned from a handler, the error handler middleware logs the full error + ID and returns only the ID to the client so they can reference it in support requests.

return errors.New(500, "database timeout")
// → logs "error_id=abc123 database timeout"
// → responds {"error": "Internal server error", "error_id": "abc123"}

func New

func New(status int, message string) *AppError

New creates an AppError with a unique ID.

func Wrap

func Wrap(status int, err error) *AppError

Wrap creates an AppError wrapping an existing error. The original error is kept for logging but not exposed to the client.

func (*AppError) Error

func (e *AppError) Error() string

Error implements the error interface.

func (*AppError) HTTPStatus

func (e *AppError) HTTPStatus() int

HTTPStatus reports the HTTP status code, satisfying router.StatusError so the router can honor it even when errors.Handler is not wired.

func (*AppError) Unwrap

func (e *AppError) Unwrap() error

Unwrap returns the wrapped error.

type DevError

type DevError struct {
	Status  int          `json:"status"`
	Message string       `json:"message"`
	Type    string       `json:"type"`
	Stack   []StackFrame `json:"stack"`
	Request *RequestInfo `json:"request,omitempty"`
	Hints   []string     `json:"hints,omitempty"`
}

DevError is the structured error object passed to the error page.

type DevPageConfig

type DevPageConfig struct {
	// Enabled turns on rich HTML error pages (typically only in development).
	Enabled bool

	// AppRoot is the project root directory for resolving source files.
	// Defaults to the current working directory.
	AppRoot string

	// ContextLines is the number of source lines shown above/below error.
	ContextLines int

	// ShowRequest shows request headers and body in the error page.
	ShowRequest bool

	// ShowEnv shows environment variables (sanitised) in the error page.
	ShowEnv bool

	// BrandName to display on the page (default: "Nimbus").
	BrandName string

	// BrandColor for the header (default: "#6366f1").
	BrandColor string
}

DevPageConfig configures the smart error page behaviour.

type HTMLPageData

type HTMLPageData struct {
	Status     int
	StatusText string
	Title      string
	Message    string
	ErrorID    string
	// Validation, when set, renders field errors (422).
	Validation map[string][]string
	// JSONPayload when set shows raw JSON for API-style errors in dev tooltips (optional).
	JSONPayload string
}

HTMLPageData is passed to the default error page template.

type HTTPError

type HTTPError struct {
	Status  int
	Message string
	Payload any
}

HTTPError represents an HTTP error with status and optional payload.

func (HTTPError) Error

func (e HTTPError) Error() string

func (HTTPError) HTTPStatus

func (e HTTPError) HTTPStatus() int

HTTPStatus reports the HTTP status code, satisfying router.StatusError so the router can honor it even when errors.Handler is not wired.

type LogReporter

type LogReporter struct{}

LogReporter is a simple reporter that logs errors to the standard logger.

func (*LogReporter) Report

func (r *LogReporter) Report(err error, context map[string]any) error

Report logs the error.

type Reporter

type Reporter interface {
	Report(err error, context map[string]any) error
}

Reporter is an interface for external error reporting services (e.g. Sentry, Bugsnag, Rollbar).

type RequestInfo

type RequestInfo struct {
	Method  string            `json:"method"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers"`
	Query   map[string]string `json:"query,omitempty"`
	Body    string            `json:"body,omitempty"`
}

RequestInfo captures request details for error diagnosis.

type SourceLine

type SourceLine struct {
	Number    int    `json:"number"`
	Code      string `json:"code"`
	Highlight bool   `json:"highlight"` // true for the error line
}

SourceLine is a line of source code with its line number.

type StackFrame

type StackFrame struct {
	File     string       `json:"file"`
	Line     int          `json:"line"`
	Function string       `json:"function"`
	Source   []SourceLine `json:"source,omitempty"`
	IsApp    bool         `json:"is_app"` // true if in the app's source tree
}

StackFrame represents a single frame in a stack trace.

Jump to

Keyboard shortcuts

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