Documentation
¶
Overview ¶
This file installs the canonical RestErrorRenderer of the Context's typed binding/response methods (BindJSON, BindParams, Count, Paginated, ...).
Package errors is the error handling system for the Iris web framework. This file holds the controller integration: it processes the errors returned by error-returning controller methods and routing functions.
Package errors is the HTTP error handling system for Iris web applications. It implements RFC 7807 (Problem Details for HTTP APIs) and lets you control how errors are processed, logged and rendered to clients.
Core Concepts ¶
The package is built around canonical error names (ErrorCodeName) that map to HTTP status codes, providing a consistent way to handle errors across your application. Each error name corresponds to a specific HTTP status code and can be used to send structured error responses to clients.
Basic Usage ¶
Register custom error codes during application initialization:
var UserNotFound = errors.Register("USER_NOT_FOUND", http.StatusNotFound)
Use error codes in your handlers:
func getUserHandler(ctx iris.Context) {
userID := ctx.Params().Get("id")
user, err := userService.GetUser(userID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
errors.NotFound.Message(ctx, "user not found")
return
}
errors.Internal.LogErr(ctx, err) // logs error and sends generic message
return
}
ctx.JSON(user)
}
Error Handling Strategies ¶
The package offers multiple approaches for error handling:
Direct error sending with custom messages: errors.InvalidArgument.Detail(ctx, "validation failed", "email format is invalid")
Automatic error processing with HandleError: if err := someOperation(); err != nil { errors.HandleError(ctx, err) // automatically determines appropriate response }
Error mapping and transformation: opts := errors.NewOptions() opts.MapErrors(errors.NotFound, sql.ErrNoRows, myapp.ErrResourceNotFound)
RFC 7807 Problem Details RFC 7807 Problem Details" aria-label="Go to RFC 7807 Problem Details">¶
The package supports RFC 7807 problem details format for structured error responses:
errors.InvalidArgument.Problem(ctx, "Validation Failed", "The email field contains an invalid email address", "https://example.com/problems/validation-failed", "/users/create")
Error Logging and Collection ¶
Configure custom error logging and collection:
opts := errors.NewOptions().
SetLogger(func(ctx iris.Context, err error) {
// Custom logging logic
logger.Error("HTTP Error", "error", err, "path", ctx.Path())
}).
SetCollector(func(ctx iris.Context, err *errors.Error) {
// Send to monitoring service
monitoring.ReportError(err)
})
Content Negotiation ¶
The package automatically handles content negotiation, sending: - JSON responses by default - HTML error pages when Accept: text/html - Problem+JSON when using Problem method with appropriate renderer
Security Considerations ¶
The package distinguishes between public and private errors:
- Public errors show detailed messages to clients
- Private errors (marked with Private() or context.ErrPrivate) show generic messages while logging full details server-side
Integration with Validation ¶
The package works with the validation sub-package for field-level validation errors, formatting them for the client without extra wiring.
See the validation sub-package documentation for detailed validation capabilities.
This file carries the error codes of this package into the sort policy of Context.BindPagination and Context.Paginated.
This file exists for its name.
It holds the generic methods of *Options and ErrorCodeMap, and it is named so that it sorts after every other file of this package that declares a method on either type: today those are error_code_map.go, map_error_as.go and options.go. The Go type checker orders a named type's methods by the file they are declared in, and file names are sorted, so this file's name decides that the generic methods come last.
Why that matters: go vet and staticcheck record what they learn about a method as a fact keyed by objectpath, and objectpath addresses a method by its index in the type's method list. On this toolchain a generic method declared before another method makes that index disagree between the package that writes the fact and the package that reads it back, so the fact lands on some other method of the type, in every program that imports this package. With the generic methods declared after all the others, no ordinary method has a generic one in front of it and the indexes agree.
So: do not add an ordinary method of *Options or ErrorCodeMap to this file, do not declare a generic method of either type anywhere else, and do not rename this file to anything that sorts before options.go. TestOptionsGenericMethodsDeclaredLast fails on all three.
The upstream bug is golang/go#81306 (export data loses method order). The context package carries the same workaround the other way round, see context/before_generic_methods_writef.go. Once go.mod requires a Go release with the fix, these methods can move next to MapErrorContains and this file and its test can go.
Index ¶
- Variables
- func ApplyPatches()
- func AsType[E error](err error) (E, bool)
- func FuncHandler(fn Func) context.Handler
- func FuncHandlers(funcs ...Func) context.Handlers
- func FuncMiddleware(handler Func) context.Handler
- func HTML(ctx *context.Context, err *Error)
- func HandleAPIError(ctx *context.Context, err error)
- func HandleError(ctx *context.Context, err error) bool
- func HandleErrorf(ctx *context.Context, err error, format string, args ...any) bool
- func HandleRequestError(ctx *context.Context, err error) bool
- func HandleRequestErrorf(ctx *context.Context, err error, format string, args ...any) bool
- func HandleRequestJSONError(ctx *context.Context, err error) bool
- func HandleResponseJSONError(ctx *context.Context, err error) bool
- func Handler(ctx *context.Context)
- func NotFoundID(ctx *context.Context, resource string, id any) bool
- func Private(err error) error
- func Problem(ctx *context.Context, err *Error)
- func RecoveryHandler(ctx *context.Context)
- func RegisterErrorCode(canonicalName ErrorCodeName, httpStatusCode int)
- func RegisterErrorCodeMap(errorMap map[ErrorCodeName]int)
- func RegisterErrorResolver(fn ErrorResolver)
- func UnwrapAll(err error) (list []error)
- type ContextErrorFunc
- type Error
- type ErrorCode
- type ErrorCodeMap
- func (m ErrorCodeMap) Filter(ctx *context.Context, err error) (ErrorCodeName, error)
- func (m ErrorCodeMap) MapErrorAs[E error](code ErrorCodeName, render func(E) *Error) ErrorCodeMap
- func (m ErrorCodeMap) MapErrorContains(e ErrorCodeName, substr, message string) ErrorCodeMap
- func (m ErrorCodeMap) MapErrorFunc(e ErrorCodeName, fn func(error) error) ErrorCodeMap
- func (m ErrorCodeMap) MapErrorFuncCtx(e ErrorCodeName, fn MapErrorFn) ErrorCodeMap
- func (m ErrorCodeMap) MapErrorTypes(e ErrorCodeName, targets ...any) ErrorCodeMap
- func (m ErrorCodeMap) MapErrorTypesTransformed(e ErrorCodeName, targets ...any) ErrorCodeMap
- func (m ErrorCodeMap) MapErrors(e ErrorCodeName, targets ...error) ErrorCodeMap
- type ErrorCodeName
- func (e ErrorCodeName) Data(ctx *context.Context, msg string, data any)
- func (e ErrorCodeName) DataWithDetail(ctx *context.Context, msg, detail string, data any)
- func (e ErrorCodeName) DenySort(message string) context.PaginationOption
- func (e ErrorCodeName) Detail(ctx *context.Context, msg, detail string)
- func (e ErrorCodeName) Detailf(ctx *context.Context, msg, detail string, detailArgs ...any)
- func (e ErrorCodeName) Err(ctx *context.Context, err error)
- func (e ErrorCodeName) ErrPrivate(ctx *context.Context, err error)
- func (e ErrorCodeName) Error() string
- func (e ErrorCodeName) Handle(ctx *context.Context, err error) bool
- func (e ErrorCodeName) Log(ctx *context.Context, format string, args ...any)
- func (e ErrorCodeName) LogErr(ctx *context.Context, err error)
- func (e ErrorCodeName) Message(ctx *context.Context, message string)
- func (e ErrorCodeName) Messagef(ctx *context.Context, format string, args ...any)
- func (e ErrorCodeName) Problem(ctx *context.Context, title, detail, typeURI, instanceURI string, extra ...any)
- func (e ErrorCodeName) Report(ctx *context.Context, err error) *Error
- func (e ErrorCodeName) String() string
- func (e ErrorCodeName) Validation(ctx *context.Context, validationErrors ...ValidationError)
- func (e ErrorCodeName) Wrap(err error) error
- type ErrorResolver
- type Func
- type IDGeneratorFunc
- type LogErrorFunc
- type MapErrorFn
- type Options
- func (opts *Options) ErrorCodeMap() ErrorCodeMap
- func (opts *Options) Handler() context.Handler
- func (opts *Options) HandlerWithError() Func
- func (opts *Options) HasRenderer() bool
- func (opts *Options) MapErrorAs[E error](code ErrorCodeName, render func(E) *Error) *Options
- func (opts *Options) MapErrorContains(e ErrorCodeName, substr, message string) *Options
- func (opts *Options) MapErrorFunc(e ErrorCodeName, fn func(error) error) *Options
- func (opts *Options) MapErrorFuncCtx(e ErrorCodeName, fn MapErrorFn) *Options
- func (opts *Options) MapErrorTypes(e ErrorCodeName, targets ...any) *Options
- func (opts *Options) MapErrors(e ErrorCodeName, targets ...error) *Options
- func (opts *Options) SetCollector(fn ContextErrorFunc) *Options
- func (opts *Options) SetID(id string) *Options
- func (opts *Options) SetIDGenerator(fn IDGeneratorFunc) *Options
- func (opts *Options) SetLogger(fn LogErrorFunc) *Options
- func (opts *Options) SetRenderer(fn ContextErrorFunc) *Options
- type Router
- func (r *Router) Any(path string, funcs ...Func) *router.RouteRegistry
- func (r *Router) Connect(path string, funcs ...Func) *router.Route
- func (r *Router) Delete(path string, funcs ...Func) *router.Route
- func (r *Router) Get(path string, funcs ...Func) *router.Route
- func (r *Router) Handle(method, path string, funcs ...Func) *router.RouteRegistry
- func (r *Router) HandleServer(path string, server ServerHandler)
- func (r *Router) Head(path string, funcs ...Func) *router.Route
- func (r *Router) Options(path string, funcs ...Func) *router.Route
- func (r *Router) Patch(path string, funcs ...Func) *router.Route
- func (r *Router) Post(path string, funcs ...Func) *router.Route
- func (r *Router) Put(path string, funcs ...Func) *router.Route
- func (r *Router) Query(path string, funcs ...Func) *router.Route
- func (r *Router) Subdomain(subdomain string, middlewareFuncs ...Func) *Router
- func (r *Router) Trace(path string, funcs ...Func) *router.Route
- func (r *Router) Use(funcs ...Func)
- func (r *Router) UseOnce(funcs ...Func)
- func (r *Router) UseRouter(funcs ...Func)
- type Routing
- type ServerHandler
- type ValidationError
- type ValidationErrors
Constants ¶
This section is empty.
Variables ¶
var ( // Is reports whether any error in err's tree matches target. It is an alias // of the standard errors.Is function, provided for convenience when working // within the errors package to avoid import conflicts. // // The tree consists of err itself followed by the sequence of errors obtained by // repeatedly calling Unwrap. When err wraps multiple errors, Is examines err // followed by a depth-first traversal of its children. // // An error is considered to match a target if it is equal to that target or if // it implements a method Is(error) bool such that Is(target) returns true. // // Example usage: // // if errors.Is(err, io.EOF) { // // Handle end of file // } Is = errors.Is // As finds the first error in err's tree that matches target, and if one is found, // sets target to that error value and returns true. It is an alias of the standard // errors.As function, provided for convenience within the errors package. // // The tree consists of err itself followed by the sequence of errors obtained by // repeatedly calling Unwrap. When err wraps multiple errors, As examines err // followed by a depth-first traversal of its children. // // An error matches target if the error's concrete value is assignable to the value // pointed to by target, or if the error has a method As(any) bool such that // As(target) returns true. // // Example usage: // // var pathError *fs.PathError // if errors.As(err, &pathError) { // fmt.Println("Failed at path:", pathError.Path) // } As = errors.As // New returns an error that formats as the given text. It is an alias of the // standard errors.New function, provided for convenience within the errors package. // // Each call to New returns a distinct error value even if the text is identical. // // Example usage: // // err := errors.New("something went wrong") New = errors.New // Unwrap returns the result of calling the Unwrap method on err, if err's type contains // an Unwrap method returning error. It is an alias of the standard errors.Unwrap function, // provided for convenience within the errors package. // // Otherwise, Unwrap returns nil. // // Example usage: // // if wrappedErr := errors.Unwrap(err); wrappedErr != nil { // // Handle the underlying error // } Unwrap = errors.Unwrap // Join returns an error that wraps the given errors. It is an alias of the standard // errors.Join function, provided for convenience within the errors package. // // Any nil error values are discarded. Join returns nil if every value in errs is nil. // The error formats as the concatenation of the strings obtained by calling the Error // method of each element of errs, with a newline between each string. // // A non-nil error returned by Join implements the Unwrap() []error method. // // Example usage: // // err1 := errors.New("first error") // err2 := errors.New("second error") // combined := errors.Join(err1, err2) Join = errors.Join )
var ( // ErrRequest is a sentinel error which can be used to indicate that error came from the request body. ErrRequest = fmt.Errorf("request error") // ErrResponse is a sentinel error which can be used to indicate that error came from the server. ErrResponse = fmt.Errorf("response error") )
var ( // ErrUnexpected is the HTTP error which sent to the client // when server fails to send an error, it's a fallback error. // The server fails to send an error on two cases: // 1. when the provided error code name is not registered (the error value is the ErrUnexpectedErrorCode) // 2. when the error contains data but cannot be encoded to json (the value of the error is the result error of json.Marshal). ErrUnexpected = Register("UNEXPECTED_ERROR", http.StatusInternalServerError) // ErrUnexpectedErrorCode is the error which logged // when the given error code name is not registered. ErrUnexpectedErrorCode = New("unexpected error code name") )
var DefaultCORSErrorHandler context.ErrorHandler = func(ctx *context.Context, err error) { FailedPrecondition.Err(ctx, err) }
DefaultCORSErrorHandler returns a context error handler which calls the FailedPrecondition.Err on any incoming error when cors middleware's HandleErrorFunc is not set.
var DefaultContextErrorHandler context.ErrorHandler = func(ctx *context.Context, err error) { HandleError(ctx, err) }
DefaultContextErrorHandler returns a context error handler which calls the HandleError on any incoming error when a rich rest response failed to be written to the client. Register it globally by calling the "ApplyPatches" function, which assigns it to the context.DefaultErrorHandler variable, or per application through iris.Options{Context: iris.ContextOptions{ErrorHandler: ...}} (or per group and route with the iris.WithErrorHandler middleware).
var DefaultPathParameterTypeErrorHandler handler.ParamErrorHandler = func(ctx *context.Context, paramIndex int, err error) { param, _ := ctx.Params().LookupByIndex(paramIndex) InvalidArgument.DataWithDetail(ctx, "invalid path parameter", err.Error(), param) }
DefaultPathParameterTypeErrorHandler registers an error handler for macro path type parameter. Register it with Application.Macros().SetErrorHandler(DefaultPathParameterTypeErrorHandler).
var DefaultRateLimitExceededHandler = func(ctx *context.Context) { tryAgainDuration := rate.Get(ctx).Delay.String() ResourceExhausted.Detailf(ctx, "rate limit exceeded", "you may try again in %s", tryAgainDuration) }
DefaultRateLimitExceededHandler is the default handler which is being used when the `ExceedHandler` is not being passed.
var DefaultVersioningNotFoundHandler = func(ctx *context.Context) { Unimplemented.Err(ctx, versioning.ErrNotFound) }
DefaultVersioningNotFoundHandler is the default not-found handler for versioning, it renders the versioning.ErrNotFound as Unimplemented in JSON format.
var SkipCanceled = true
SkipCanceled is a package-level setting which by default skips the logging of a canceled response or operation. See the "Context.IsCanceled()" method and "iris.IsCanceled()" function that decide if the error is caused by a canceled operation.
Change of this setting MUST be done on initialization of the program.
Functions ¶
func ApplyPatches ¶
func ApplyPatches()
ApplyPatches registers the DefaultPathParameterTypeErrorHandler, DefaultContextErrorHandler, DefaultRateLimitExceededHandler, DefaultVersioningNotFoundHandler and DefaultCORSErrorHandler to their default places in order to be used by the Iris' router and middleware system globally. It should be called before any server starts. Usage:
func init() { errors.ApplyPatches() }
func AsType ¶
AsType is the standard library's errors.AsType.
It finds the first error in err's tree that is an E and returns it, with no target variable to declare first:
if quota, ok := errors.AsType[*QuotaError](err); ok {
fmt.Println("the limit is", quota.Limit)
}
It is a function and not a variable like Is and As above, because a generic function cannot be assigned without naming its type argument.
func FuncHandler ¶
FuncHandler converts an error-returning function into a standard Iris handler with automatic error handling. This enables a cleaner, more functional programming style for HTTP handlers by eliminating repetitive error handling boilerplate code.
The returned handler sends any error through the error handling pipeline: mapping, transformation, logging and the client response.
Parameters:
- fn: An error-returning function that implements the Func signature
Returns:
- context.Handler: A standard Iris handler that automatically handles errors
- nil: If the input function is nil
Error Processing: When the wrapped function returns an error, it is automatically processed through: 1. Error mapping and transformation (if configured via Options) 2. Validation error handling for structured field-level errors 3. Security-conscious private error filtering 4. Appropriate HTTP status code determination 5. JSON response generation with error details 6. Logging and error collection (if configured)
Example usage:
// Define error-returning handler function
func getUserProfile(ctx iris.Context) error {
userID := ctx.Values().GetString("user_id")
if userID == "" {
return errors.Unauthenticated.Wrap(fmt.Errorf("user not authenticated"))
}
profile, err := profileService.GetProfile(userID)
if err != nil {
return err // Automatic error handling
}
ctx.JSON(profile)
return nil
}
// Register with automatic error handling
app.Get("/profile", errors.FuncHandler(getUserProfile))
// Using with middleware chain
app.Get("/admin/users",
authMiddleware,
errors.FuncHandler(listUsers),
auditMiddleware)
Advantages over traditional handlers: - Eliminates repetitive error handling code - Ensures consistent error response formatting - Automatic integration with error mapping and logging - Cleaner, more readable handler code - Better error context preservation
Performance: The wrapper introduces minimal overhead, primarily the error check and potential error processing. Successful requests have negligible impact.
Integration: Fully compatible with Iris middleware chains, route groups, and the broader error handling ecosystem including Options configuration.
func FuncHandlers ¶
FuncHandlers converts multiple error-returning functions into a slice of standard Iris handlers with automatic error handling. It converts several Func values at once and drops any that are nil.
Each function in the input slice is individually wrapped with automatic error handling through FuncHandler, creating a slice of context.Handler instances that can be used directly with Iris routing methods that accept multiple handlers.
Parameters:
- funcs: A variadic list of error-returning functions implementing the Func signature
Returns:
- context.Handlers: A slice of standard Iris handlers with automatic error handling
- nil: If no valid functions are provided or all functions are nil
Filtering Behavior: - Nil functions are automatically filtered out and excluded from the result - The resulting slice contains only valid, wrapped handlers - If all input functions are nil, the function returns nil
Example usage:
// Define multiple error-returning handlers
func validateRequest(ctx iris.Context) error {
// Validation logic
return nil
}
func processData(ctx iris.Context) error {
// Data processing logic
return nil
}
func generateResponse(ctx iris.Context) error {
// Response generation logic
return nil
}
// Convert all functions to handlers with error handling
handlers := errors.FuncHandlers(validateRequest, processData, generateResponse)
// Use with route registration
app.Post("/api/process", handlers...)
// Combine with traditional handlers
allHandlers := append([]context.Handler{authMiddleware}, handlers...)
app.Put("/api/update", allHandlers...)
Advanced usage with conditional handlers:
// Some handlers might be conditionally nil
var optionalHandler errors.Func
if features.EnableAdvancedProcessing {
optionalHandler = advancedProcessingHandler
}
handlers := errors.FuncHandlers(
validateRequest,
optionalHandler, // Automatically filtered if nil
generateResponse,
)
Performance: Each function is individually wrapped, so the performance characteristics are identical to calling FuncHandler multiple times. The overhead is minimal and proportional to the number of valid functions provided.
Use Cases: - Pipeline-style request processing with multiple stages - Batch conversion of error-returning functions - Building reusable handler chains with automatic error handling - Simplifying route registration with multiple handlers
func FuncMiddleware ¶
FuncMiddleware converts an error-returning function into a middleware handler with automatic error handling and request pipeline continuation. This function enables middleware components to use the same error-handling patterns as regular handlers while maintaining proper middleware semantics.
Unlike FuncHandler which is designed for terminal handlers, FuncMiddleware is specifically designed for middleware components that need to: 1. Perform preprocessing or validation 2. Potentially stop the request pipeline on errors 3. Continue to the next middleware/handler on success
Parameters:
- handler: An error-returning function that implements the Func signature
Returns:
- context.Handler: A standard Iris middleware that automatically handles errors
Middleware Behavior: - On Success (nil error): Calls ctx.Next() to continue the request pipeline - On Error (non-nil error): Processes error through HandleError() and stops execution - Error handling includes all standard features: mapping, logging, response generation
Example usage:
// Authentication middleware
func authenticateUser(ctx iris.Context) error {
token := ctx.Header("Authorization")
if token == "" {
return errors.Unauthenticated.Wrap(fmt.Errorf("missing authorization header"))
}
user, err := authService.ValidateToken(token)
if err != nil {
return errors.Unauthenticated.Wrap(err)
}
ctx.Values().Set("user", user)
return nil // Success - continue pipeline
}
// Register as middleware
app.Use(errors.FuncMiddleware(authenticateUser))
// Input validation middleware
func validateJSONInput(ctx iris.Context) error {
var input map[string]any
if err := ctx.ReadJSON(&input); err != nil {
return errors.InvalidArgument.Wrap(err)
}
if err := inputValidator.Validate(input); err != nil {
return errors.InvalidArgument.Wrap(err)
}
ctx.Values().Set("validated_input", input)
return nil
}
// Rate limiting middleware
func rateLimitMiddleware(ctx iris.Context) error {
clientIP := ctx.RemoteAddr()
if !rateLimiter.Allow(clientIP) {
return errors.ResourceExhausted.Wrap(fmt.Errorf("rate limit exceeded"))
}
return nil
}
// Chain multiple error-aware middleware
app.Use(
errors.FuncMiddleware(rateLimitMiddleware),
errors.FuncMiddleware(authenticateUser),
errors.FuncMiddleware(validateJSONInput),
)
Advanced usage with conditional processing:
func conditionalProcessing(ctx iris.Context) error {
if ctx.Method() == "POST" {
// Only validate POST requests
if err := validatePostData(ctx); err != nil {
return err
}
}
// Always log request
logRequest(ctx)
return nil
}
Error Handling Flow: 1. Middleware function executes 2. If error returned: HandleError() processes it and stops request 3. If nil returned: ctx.Next() continues to next middleware/handler 4. All error processing features available: mapping, logging, collection, etc.
Performance: Minimal overhead for successful requests (single error check + ctx.Next()). Error cases have the same performance characteristics as other error handling paths.
Thread Safety: Fully thread-safe and compatible with concurrent request processing.
Integration: works alongside other Iris middleware and honours the error handling Options.
func HTML ¶
HTML is a renderer which renders the error as an HTML page. The view engine should be registered before using this renderer. The error's status code is used as a part of the template name e.g. /errors/500.html.
Usage:
opts := errors.NewOptions() opts.SetRenderer(errors.HTML)
func HandleAPIError ¶
HandleAPIError handles remote server errors. Optionally, use it when you write your server's HTTP clients using the the /client package. When the HTTP Client sends data to a remote server but that remote server failed to accept the request as expected, then the error will be proxied to this server's end-client.
When the given "err" is not a type of client.APIError then the error will be sent using the "Internal.LogErr" method which sends HTTP internal server error to the end-client and prints the "err" using the "LogError" package-level function.
func HandleError ¶
HandleError provides automatic error processing and client response generation based on error type analysis and registered error mappings. This function serves as the primary entry point for error handling in Iris applications using this package.
The function performs intelligent error analysis and routing:
1. Determines if the error originated from client request vs server processing 2. Checks for validation errors and formats them appropriately 3. Applies registered error mappings (see Options.MapErrors, MapErrorFunc) 4. Handles special error types (database errors, JSON errors, API errors) 5. Wraps unrecognized errors with appropriate error codes 6. Sends formatted responses to clients
Error Processing Priority:
- ValidationError/ValidationErrors: Formatted as field-level validation failures
- ErrorCodeName wrapped errors: Uses the specific error code for response
- Mapped errors: Applied through ErrorCodeMap transformations
- Registered ErrorResolvers: e.g. the pgerrors subpackage maps pg.ErrNoRows → NotFound and duplicate key → AlreadyExists
- JSON parsing errors: Detailed syntax error information
- API errors: Proxied from remote services
- Unknown errors: Wrapped as Internal server errors
Parameters:
- ctx: The Iris request context for the current HTTP request
- err: The error to be processed and sent to the client
Returns:
- bool: true if the error was successfully handled and a response sent, false otherwise
Example usage:
func createUser(ctx iris.Context) {
var user User
if err := ctx.ReadJSON(&user); err != nil {
if errors.HandleError(ctx, err) {
return // Error was handled and response sent
}
}
if err := userService.CreateUser(user); err != nil {
errors.HandleError(ctx, err) // Automatic error type detection
return
}
ctx.JSON(user)
}
The function respects the ErrRequest sentinel error for distinguishing between client-side and server-side errors, affecting whether errors are logged as InvalidArgument (400) or Internal (500) responses.
See also HandleRequestError for forcing client-side error interpretation, and the Options type for configuring error mapping and processing behavior.
func HandleErrorf ¶
HandleErrorf wraps "err" with request-specific detail and handles the result exactly like HandleError. The wrap uses %w, so mappings registered through Options.MapErrors, MapErrorTypes and errors.Is/As classification still apply:
// renders the mapped 404 with message "plan with id: 42: plan not found". errors.HandleErrorf(ctx, err, "plan with id: %s", id)
Mapping functions that inspect the error text observe the prefixed message. It returns false without writing a response when "err" is nil.
func HandleRequestError ¶
HandleRequestError processes errors with the assumption that they originated from client request issues rather than server-side problems. This function behaves identically to HandleError except that unrecognized errors are treated as client errors (InvalidArgument/400) rather than server errors (Internal/500).
This function is useful in scenarios where you're processing user input, validating request data, or handling operations where errors are likely to be caused by invalid client requests rather than internal server issues.
Parameters:
- ctx: The Iris request context for the current HTTP request
- err: The error to be processed as a client request error
Returns:
- bool: true if the error was successfully handled and a response sent, false otherwise
Example usage:
func validateUserInput(ctx iris.Context) {
var input UserInput
if err := ctx.ReadJSON(&input); err != nil {
errors.HandleRequestError(ctx, err) // Treat as client error (400)
return
}
if err := validateBusinessRules(input); err != nil {
errors.HandleRequestError(ctx, err) // Client sent invalid data
return
}
}
The key difference from HandleError is error classification: - HandleError: Unknown errors → Internal (500) - HandleRequestError: Unknown errors → InvalidArgument (400)
All other error processing logic (validation errors, mapped errors, etc.) remains identical.
See HandleError for complete error processing documentation.
func HandleRequestErrorf ¶
HandleRequestErrorf is the HandleRequestError counterpart of HandleErrorf: same wrapping and classification, but unrecognized errors render as client errors (InvalidArgument) instead of internal ones.
func HandleRequestJSONError ¶
HandleRequestJSONError handles a failure to decode a request body as JSON. It answers 400 with a detail that names only wire-level facts (an empty body, malformed JSON, the offending field and the expected kind), never the server's Go types. It reports whether a response was sent; a nil error and an error that is not a JSON one report false.
func HandleResponseJSONError ¶
HandleResponseJSONError handles a failure to encode a response as JSON. It answers 500 with a generic detail and reports whether a response was sent; a nil error and an error that is not a JSON one report false.
func Handler ¶
Handler answers both router-level errors (404, 405) and application-level errors with one consistent JSON shape and the matching HTTP status code.
This handler serves as a universal error processing middleware that can be applied globally or to specific route groups to ensure all errors are handled uniformly throughout the application.
Error Processing Flow: 1. Determine if the current request matched a registered route 2. For router errors (404/405): Generate appropriate error responses with helpful details 3. For application errors: Process any errors set via ctx.StopWithError() or similar methods 4. Apply error transformation and formatting through the configured error handling pipeline 5. Send structured JSON responses to clients with appropriate HTTP status codes
Router Error Handling: - 404 Not Found: sends the HTTP status text ("Not Found") as the message and the fixed "The requested page could not be found." text as the detail; no request path is included - 405 Method Not Allowed: Includes allowed methods from the Allow header when available
Application Error Handling:
After the chain returns, a status of 400 or above with nothing written is rendered. The chain does not have to be stopped: ctx.StopWithStatus(403) and ctx.NotFound() are treated alike. What the client reads depends on the error stored on the Context, if any (ctx.StopWithError, ctx.StopWithPlainError, ctx.SetErr):
- no stored error: the status text is the message ("Forbidden");
- a private error (context.PrivateError, ctx.SetErrPrivate, or an error with a private one anywhere in its chain, which is what errors.Private builds): nothing of it is shown, whatever its type, and no mapping is asked about it. The status stays the one the handler set. Below 500 the status text is the message and there is no detail. At 500 and above the error goes to the configured logger and the client reads the generic "server error" message. The private text reaches the collector, not the client;
- an error a mapping recognises, and that is not private (Options.MapErrors and its siblings, a registered ErrorResolver, a validation error, a wrapped ErrorCodeName): it renders through that mapping, with the mapping's status;
- any other error, on a status of 500 or above: the error goes to the configured logger and the client reads the generic "server error" message. A store that is down must not have its address read by a client because whoever stored the error forgot to mark it. The status stays the one the handler set: a 503 is a 503. There is one exception: a stored *errors.Error that is not private is sent as it is, because it was built for the client;
- any other error, below 500: its text is the message. It was written for the client ("name is required").
Nothing is rendered when a body was written, when the status line is already on the wire (a flush with no body yet) or when the connection was hijacked: there is no response left to write, and a document appended to one the client has started to read corrupts it. Nothing is rendered either when the response declares a Content-Length: whoever declared it chose the body, an empty one included, as a standard handler does when it relays an upstream's empty 401. A status below 400 is never touched.
Where it is registered decides what it covers:
- app.Use(errors.Handler) on the root application covers the routes and the router's own 404 and 405. A HandleNoRoute or HandleNoMethod handler registered after it never runs: in those two chains this handler answers and does not call the next one.
- app.UseRouter(errors.Handler) covers the routes and everything registered after it with UseRouter. It does not cover 404 and 405: it runs before the router, and by the time the chain returns the router's default handler has written the status text.
- app.HandleNoRoute(errors.Handler) and app.HandleNoMethod(errors.Handler) cover 404 and 405 only.
iris.NewBuilder registers it for you: with UseRouter as the last of its built-in middleware, after compression, and as the 404 and the 405 handler when the application registered none of its own. httptest.NewController registers it with UseRouter and as the 404 handler.
Usage Examples:
// Global error handling for entire application
app.Use(errors.Handler)
// Router-level error handling: the routes and the pre-routing middleware
// registered after it, and the router's own 404 and 405
app.UseRouter(errors.Handler)
app.HandleNoRoute(errors.Handler)
app.HandleNoMethod(errors.Handler)
// Route group specific error handling
apiGroup := app.Party("/api")
apiGroup.Use(errors.Handler)
// Combined with custom error configuration
opts := errors.NewOptions().
MapErrors(errors.NotFound, sql.ErrNoRows).
SetRenderer(errors.HTML)
app.Use(opts.Handler(), errors.Handler)
Error Response Format: All errors are formatted as JSON responses following the standard Error struct format:
{
"id": "req-12345",
"http_error_code": {
"canonical_name": "NOT_FOUND",
"status": 404
},
"message": "Not Found",
"detail": "The requested page could not be found."
}
Security Considerations: - A private error (context.PrivateError, ctx.SetErrPrivate, errors.Private) never has its text sent to a client, through a mapping or otherwise - An unmapped error on a status of 500 or above is logged and never has its text sent either, unless it is a *errors.Error that is not private - Error IDs enable correlation between client-facing errors and server-side logs
Performance Notes: - Minimal overhead for successful requests (early returns) - Efficient status code mapping using pre-computed maps - Lazy error code generation only when needed
Integration: this handler honours the rest of the error handling system, including Options configuration, error mapping, custom renderers and logging.
func NotFoundID ¶
NotFoundID renders NOT_FOUND with the detail "<resource> <id> not found", so the whole "this row is not there" answer is one line:
func getPlan(ctx iris.Context) {
plan, err := svc.GetPlan(ctx, id)
if errors.HandleError(ctx, err) {
return
}
if plan == nil {
errors.NotFoundID(ctx, "plan", id)
return
}
ctx.OK(plan, nil)
}
The result follows the Context.OK convention, true meaning the handler succeeded, so it is always false here; return it directly only from a helper which itself reports that. Note that HandleError in this package reports the opposite, true when it wrote the response, which is why the example above tests it and ignores this one.
The id is formatted with %v, so a string, an integer and a uuid.UUID all read the way they print.
func Private ¶
Private wraps the given error with the private error wrapper. It's useful when you want to log the full error but send a generic message to the client, from the `MapErrorFunc`, `MapErrorFuncCtx`, `MapErrors` and `MapErrorTypes` methods of the `Options` type.
Usage:
MapErrorFunc(errors.Internal, func(err error) error {
if errText := err.Error(); strings.Contains(errText, `syntax error at or near \"`) ||
strings.Contains(errText, "transaction: ") { // contains query information.
return errors.Private(err)
}
return nil
}).
// And then you may continue with error type mapping as well. MapErrorTypes(errors.InvalidArgument, app.MyDomainLevelError1{}, app.MyDomainLevelError2{}, ).
func Problem ¶
Problem is a renderer which renders an error as a problem details object as defined in RFC 7807. The object must contain the following members: - type: A URI reference that identifies the problem type. - title: A short, human-readable summary of the problem type. - status: The HTTP status code generated by the origin server for this occurrence of the problem. - detail: A human-readable explanation specific to this occurrence of the problem. - instance: A URI reference that identifies the specific occurrence of the problem.
For more details, see RFC 7807: https://datatracker.ietf.org/doc/html/rfc7807.
func RecoveryHandler ¶
RecoveryHandler is a middleware which recovers from panics and sends an appropriate error response to the logger and the client.
func RegisterErrorCode ¶
func RegisterErrorCode(canonicalName ErrorCodeName, httpStatusCode int)
RegisterErrorCode registers a canonical error name with its associated HTTP status code in the global error registry. This function is used internally by Register() and can be called directly when you need more control over the registration process.
The function updates multiple internal data structures: - Maps the canonical name to its ErrorCode metadata - Maintains ordered lists of status codes for consistent error processing - Groups error names by status code for lookup operations
Parameters:
- canonicalName: The ErrorCodeName identifier for this error type
- httpStatusCode: The HTTP status code that should be returned for this error
Example usage:
const UserBlocked ErrorCodeName = "USER_BLOCKED" errors.RegisterErrorCode(UserBlocked, http.StatusForbidden)
Thread Safety: This function must be called during application initialization before the HTTP server starts. The internal registry is not protected by mutex for performance reasons, making concurrent registration unsafe.
See also Register() for a more convenient registration method that returns the ErrorCodeName.
func RegisterErrorCodeMap ¶
func RegisterErrorCodeMap(errorMap map[ErrorCodeName]int)
RegisterErrorCodeMap registers multiple error codes at once from a map of canonical names to HTTP status codes. This function is useful when you have many error codes to register or when loading error configurations from external sources.
The function iterates through the provided map and calls RegisterErrorCode for each entry, maintaining all the same guarantees and requirements as individual registration.
Parameters:
- errorMap: A map where keys are ErrorCodeName identifiers and values are HTTP status codes
Example usage:
errorMap := map[errors.ErrorCodeName]int{
"USER_NOT_FOUND": http.StatusNotFound,
"INVALID_TOKEN": http.StatusUnauthorized,
"QUOTA_EXCEEDED": http.StatusTooManyRequests,
"MAINTENANCE_MODE": http.StatusServiceUnavailable,
}
errors.RegisterErrorCodeMap(errorMap)
The function safely handles empty maps and will return immediately without side effects if the provided map is nil or empty.
Thread Safety: Like other registration functions, this must be called during application initialization before the HTTP server starts. Concurrent registration is not safe.
See also Register() and RegisterErrorCode() for individual error registration.
func RegisterErrorResolver ¶
func RegisterErrorResolver(fn ErrorResolver)
RegisterErrorResolver registers fn to run inside HandleError for errors the per-route Options code map did not claim. Register at init time or before serving; the first resolver that reports true stops the chain.
func UnwrapAll ¶
UnwrapAll recursively unwraps an error and returns a slice containing all errors in the wrapping chain, starting with the top-level error. This function handles both single-error wrapping (via Unwrap() error) and multi-error wrapping (via Unwrap() []error), so the whole error tree is visible.
The function traverses the error chain depth-first, collecting all errors encountered. For errors that wrap multiple errors (implementing Unwrap() []error), it recursively processes each wrapped error.
Example usage:
// Single error chain
err1 := errors.New("root cause")
err2 := fmt.Errorf("wrapper: %w", err1)
err3 := fmt.Errorf("top level: %w", err2)
allErrors := errors.UnwrapAll(err3)
// allErrors contains: [err3, err2, err1]
// Multi-error case
err1 := errors.New("first error")
err2 := errors.New("second error")
combined := errors.Join(err1, err2)
allErrors := errors.UnwrapAll(combined)
// allErrors contains: [combined, err1, err2]
Returns an empty slice if the input error is nil.
Types ¶
type ContextErrorFunc ¶
ContextErrorFunc defines the signature for functions that process Error instances within the context of an HTTP request. These functions are used for both error collection (monitoring, analytics) and error rendering (response formatting).
The function receives the current request context and a fully-constructed Error instance containing all error details including ID, error code, message, validation information, and any additional data.
Collection Use Cases: - Sending errors to monitoring services (Datadog, New Relic, etc.) - Storing errors in databases for analysis - Triggering alerts based on error patterns - Building error dashboards and metrics
Rendering Use Cases: - Custom JSON formatting - HTML error page generation - XML or other format responses - Problem+JSON (RFC 7807) formatting
Implementation Examples:
// Error collection for monitoring
func monitoringCollector(ctx iris.Context, err *Error) {
go func() { // Non-blocking collection
monitoring.ReportError(monitoring.ErrorEvent{
ID: err.ID,
Code: string(err.ErrorCode.CanonicalName),
Message: err.Message,
Timestamp: time.Now(),
RequestID: ctx.ID(),
UserID: ctx.Values().GetString("user_id"),
})
}()
}
// Custom JSON rendering
func customJSONRenderer(ctx iris.Context, err *Error) {
response := map[string]any{
"success": false,
"error_code": err.ErrorCode.CanonicalName,
"message": err.Message,
"timestamp": time.Now().Unix(),
}
ctx.JSON(response)
}
Performance Note: Collection functions should avoid blocking operations or perform them in separate goroutines to prevent request processing delays.
type Error ¶
type Error struct {
// ID helps to track the error, it's a unique identifier.
ID string `json:"id,omitempty" yaml:"ID,omitempty"`
// ErrorCode is the canonical name and the status code of the error.
ErrorCode ErrorCode `json:"http_error_code" yaml:"HTTPErrorCode"`
// Message is the human-readable message of the error.
Message string `json:"message,omitempty" yaml:"Message"`
// Detail is the human-readable explanation specific to this occurrence of the error.
Detail string `json:"detail,omitempty" yaml:"Detail"`
// Type is the URI reference that identifies the problem type.
// It's a field, part of the RFC 7807. Example: https://example.com/probs/out-of-credit.
Type string `json:"type,omitempty" yaml:"Type,omitempty"`
// Instance is the URI reference that identifies the specific occurrence of the problem.
// It's a field, part of the RFC 7807. Example: /account/kataras/messages/1.
Instance string `json:"instance,omitempty" yaml:"Instance,omitempty"`
// Validation is the validation error, if any.
Validation any `json:"validation,omitempty" yaml:"Validation,omitempty"`
// Data is the custom (JSON) extra data of the error, if any.
Data json.RawMessage `json:"data,omitempty" yaml:"Data,omitempty"`
}
Error represents the JSON form of "http wire errors".
Examples can be found at:
https://github.com/kataras/iris/tree/main/_examples/08-errors/central-error-map.
func Report ¶
Report runs the full error pipeline and returns the resulting Error without writing anything to the response.
It exists for responses that have already committed a status code, which is every streaming response after its first byte. The ordinary path cannot help there: ErrorCodeName.Err and its relatives end in a render, and a render in the middle of an event stream writes a JSON body into the stream and corrupts it. Skipping the pipeline instead is worse, because it is the only thing that makes a failure visible: the logger and the collector are what carry an error to a cloud sink, and a stream that fails silently is a stream nobody knows failed.
Report does everything the render path does except render:
- resolves the error against the route's error-code map, so mappings registered through Options.MapErrors and friends apply exactly as they do to an ordinary response;
- honours the global SkipCanceled setting, so a client that hung up does not page anyone. That is decided by the request's own context, never by the error's shape: an upstream timeout looks like a deadline to errors.Is and is still reported;
- calls the logger, which is the package-level LogError unless a route set its own. This is the hook a cloud logger replaces, so a stream failure reaches it with no extra wiring;
- generates the correlation id through Options.SetIDGenerator;
- redacts a private or internal error down to a generic message, exactly as the renderer would, so nothing internal reaches the client;
- calls the collector with the finished Error.
It returns nil when there is nothing to report: a nil error, or a cancellation while SkipCanceled is on. The returned value is safe to send to the client; the unredacted original went to the logger and the collector.
The sse package uses this to render its error frame, so a streaming handler gets the same treatment as any other without asking for it.
func (*Error) Attrs ¶
Attrs returns the slog's attributes (and golog supports them) for this error. It's just a helper function to make your life easier.
type ErrorCode ¶
type ErrorCode struct {
CanonicalName ErrorCodeName `json:"canonical_name" yaml:"CanonicalName"`
Status int `json:"status" yaml:"Status"`
}
ErrorCode represents the structured metadata for an HTTP error, containing both the canonical name and associated HTTP status code. This type is used internally for error processing and is included in JSON error responses sent to clients.
The ErrorCode provides the bridge between logical error names (like "USER_NOT_FOUND") and HTTP protocol specifics (like status code 404), enabling consistent error handling across different layers of the application.
This type is automatically populated when registering error codes and should not be created directly by application code.
func (ErrorCode) ServeFailure ¶
func (errorCode ErrorCode) ServeFailure(ctx *context.Context, msg, detail, typeURI, instanceURI string, validationErrors any, dataValue any, isPrivate bool)
ServeFailure handles the error response for a given Iris request context. It constructs an error object with the provided details and sends it to the client. The method also logs the error and optionally sends a generic message to the client if the error is marked as private.
Parameters: - ctx: The context of the request. - msg: The error message to be sent to the client. - detail: Additional details about the error. - typeURI: A URI reference that identifies the problem type. - instanceURI: A URI reference that identifies the specific occurrence of the problem. - validationErrors: Any validation errors related to the request. - dataValue: Additional data to be included in the error response. - isPrivate: A boolean indicating whether the error details should be hidden from the client.
The method performs the following steps: 1. Converts the dataValue to a JSON raw message if it is not nil. 2. Constructs an Error object with the provided details. 3. Logs the error and collects it using the configured options. 4. If the error is marked as private, replaces the error details with generic messages. 5. Sets the HTTP status code and stops further execution. 6. Renders the error response as HTML if the requested content type is HTML, otherwise uses a custom renderer or defaults to JSON.
type ErrorCodeMap ¶
type ErrorCodeMap map[ErrorCodeName][]MapErrorFn
ErrorCodeMap provides a sophisticated error mapping and transformation system that enables automatic classification of errors into appropriate HTTP status codes and ErrorCodeName categories. This type serves as the core engine for intelligent error handling in Iris applications.
The ErrorCodeMap associates ErrorCodeName identifiers with lists of transformation functions that can analyze, modify, or replace incoming errors. When an error occurs, the map is consulted to determine the most appropriate HTTP response based on error characteristics.
Key Features: - Automatic error classification using multiple strategies - Priority-based processing ordered by HTTP status codes - Support for error wrapping and unwrapping chains - Type-based error matching with interface support - Custom transformation functions for complex error scenarios - Fallback mechanisms for unhandled error types
Error Processing Pipeline: 1. Iterate through registered ErrorCodeNames ordered by HTTP status code (lower to higher) 2. For each ErrorCodeName, execute associated transformation functions in registration order 3. Return the first non-nil error result along with its associated ErrorCodeName 4. If no functions handle the error, return the original error without classification
Mapping Strategies:
// Direct error instance mapping
codeMap.MapErrors(errors.NotFound, sql.ErrNoRows, gorm.ErrRecordNotFound)
// Type-based mapping
codeMap.MapErrorTypes(errors.InvalidArgument, MyValidationError{})
// Custom transformation functions
codeMap.MapErrorFunc(errors.Internal, func(err error) error {
if strings.Contains(err.Error(), "connection refused") {
return errors.Private(err) // Hide sensitive details
}
return nil // Let other mappings handle this error
})
Usage Examples:
// Create and configure error mapping
codeMap := make(ErrorCodeMap)
codeMap.MapErrors(errors.NotFound, sql.ErrNoRows)
codeMap.MapErrorTypes(errors.InvalidArgument, ValidationError{})
// Use with Options for automatic error handling
opts := errors.NewOptions()
opts.codeMap = codeMap
// Manual error classification (ctx may be nil for direct calls)
errorCode, transformedErr := codeMap.Filter(ctx, originalErr)
if errorCode != "" {
errorCode.Err(ctx, transformedErr)
}
Thread Safety: ErrorCodeMap instances are not thread-safe and should be configured during application initialization before the HTTP server starts. Concurrent access during runtime may result in undefined behavior.
See Options.MapErrors, Options.MapErrorTypes, Options.MapErrorFunc and Options.MapErrorFuncCtx for convenient configuration methods that wrap this functionality.
func (ErrorCodeMap) Filter ¶
func (m ErrorCodeMap) Filter(ctx *context.Context, err error) (ErrorCodeName, error)
Filter performs error classification and transformation by applying all registered mapping functions to determine the most appropriate ErrorCodeName and transformed error for the given input error. This method implements the core logic of the error mapping system.
The method processes mappings in a specific order to ensure consistent and predictable error classification: 1. Iterate through HTTP status codes in ascending order (400, 401, 404, 500, etc.) 2. For each status code, process all associated ErrorCodeNames 3. For each ErrorCodeName, execute mapping functions in registration order 4. Return the first successful mapping (non-nil error result)
This ordering ensures that more specific error types (typically with lower status codes) are checked before more general ones, allowing for precise error classification while maintaining predictable fallback behavior.
Parameters:
- ctx: The request context, forwarded to context-aware mapping functions (registered through MapErrorFuncCtx). It may be nil when Filter is called directly, outside a request; context-aware functions must tolerate that.
- err: The original error to be classified and potentially transformed
Returns:
- ErrorCodeName: The determined error code name, empty string if no mapping found
- error: The transformed error to be sent to the client, original error if no transformation
Transformation Process: Each mapping function receives the original error and can: - Return nil to indicate it doesn't handle this error type - Return the same error unchanged (classification only) - Return a modified error with additional context or formatting - Return a completely different error (replacement)
Example mappings and their results:
// Direct error instance mapping
codeMap.MapErrors(errors.NotFound, sql.ErrNoRows)
// sql.ErrNoRows -> (errors.NotFound, sql.ErrNoRows)
// Type-based mapping with transformation
codeMap.MapErrorTypes(errors.InvalidArgument, ValidationError{})
// MyValidationError{Field: "email"} -> (errors.InvalidArgument, MyValidationError{Field: "email"})
// Custom transformation
codeMap.MapErrorFunc(errors.Internal, func(err error) error {
if strings.Contains(err.Error(), "database") {
return fmt.Errorf("storage service temporarily unavailable")
}
return nil
})
// database error -> (errors.Internal, "storage service temporarily unavailable")
Performance Characteristics: - Time complexity: O(n*m*k) where n=status codes, m=error codes per status, k=functions per error code - Space complexity: O(1) for processing (mapping storage is separate) - Early termination on first successful mapping for efficiency
Thread Safety: This method is read-only and safe for concurrent use after the ErrorCodeMap has been fully configured during application initialization.
func (ErrorCodeMap) MapErrorAs ¶
func (m ErrorCodeMap) MapErrorAs[E error](code ErrorCodeName, render func(E) *Error) ErrorCodeMap
MapErrorAs registers a typed error mapping. See Options.MapErrorAs for the full documentation.
func (ErrorCodeMap) MapErrorContains ¶
func (m ErrorCodeMap) MapErrorContains(e ErrorCodeName, substr, message string) ErrorCodeMap
MapErrorContains registers a substring mapping. See Options.MapErrorContains for the full documentation.
func (ErrorCodeMap) MapErrorFunc ¶
func (m ErrorCodeMap) MapErrorFunc(e ErrorCodeName, fn func(error) error) ErrorCodeMap
MapErrorFunc registers a custom error transformation function that provides the most flexible error mapping capability. This method allows complex error analysis, conditional processing, and sophisticated error transformation logic that goes beyond simple type or instance matching.
The transformation function receives an error and can: - Return nil to indicate it doesn't handle this error (allows other mappings to be tried) - Return the same error unchanged (classification without transformation) - Return a modified version of the error (enhancement or formatting) - Return a completely different error (replacement or abstraction)
Multiple functions can be registered for the same ErrorCodeName and will be executed in registration order until one returns a non-nil error. This enables layered processing and fallback mechanisms.
Parameters:
- e: The ErrorCodeName to associate with this transformation function
- fn: The transformation function that processes incoming errors
Function Signature:
- Input: error - The original error to be analyzed and potentially transformed
- Output: error - The processed error, or nil if this function doesn't handle it
Example implementations:
// Database error abstraction
codeMap.MapErrorFunc(errors.Internal, func(err error) error {
if strings.Contains(err.Error(), "connection refused") {
return errors.Private(fmt.Errorf("database service unavailable"))
}
if strings.Contains(err.Error(), "timeout") {
return fmt.Errorf("operation timed out, please try again")
}
return nil // Let other mappings handle this error
})
// Third-party service error mapping
codeMap.MapErrorFunc(errors.Unavailable, func(err error) error {
if stripeErr, ok := err.(*stripe.Error); ok {
return &errors.Error{
Message: "payment processing temporarily unavailable",
Detail: stripeErr.Msg,
Data: json.RawMessage(fmt.Sprintf(`{"stripe_code":"%s"}`, stripeErr.Code)),
}
}
return nil
})
// Validation error enhancement
codeMap.MapErrorFunc(errors.InvalidArgument, func(err error) error {
if validationErr, ok := err.(ValidationError); ok {
return fmt.Errorf("validation failed for field '%s': %s",
validationErr.Field(), validationErr.Reason())
}
return nil
})
Thread Safety: This method must be called during application initialization before the HTTP server starts, as the internal mapping structures are not protected by mutex.
Registration Order: Functions are stored in a slice and executed in registration order, so registering the more specific handlers before the general ones gives you priority-based processing.
func (ErrorCodeMap) MapErrorFuncCtx ¶
func (m ErrorCodeMap) MapErrorFuncCtx(e ErrorCodeName, fn MapErrorFn) ErrorCodeMap
MapErrorFuncCtx registers a context-aware error transformation function: it works exactly like MapErrorFunc but the function also receives the request context, so the transformed error can carry request detail (path, user, values) or trigger request-scoped side effects.
codeMap.MapErrorFuncCtx(errors.NotFound, func(ctx *context.Context, err error) error {
if errors.Is(err, ErrPlanNotFound) {
return fmt.Errorf("%s: %w", ctx.Path(), err)
}
return nil
})
The context is nil when Filter is called directly, outside a request; context-aware functions must tolerate a nil context.
func (ErrorCodeMap) MapErrorTypes ¶
func (m ErrorCodeMap) MapErrorTypes(e ErrorCodeName, targets ...any) ErrorCodeMap
MapErrorTypes registers error types that should be automatically mapped to a particular ErrorCodeName when encountered. This method provides type-based error matching using Go's type system and reflection, making it ideal for mapping custom error types, interface implementations, and hierarchical error structures.
Type matching works with: - Concrete types (structs, built-in types) - Interface types (any error implementing the interface) - Pointer types (both *Type and Type will match appropriately) - Embedded error types within larger structures
When a matching error type is encountered, the original error is returned unchanged, preserving all error context and details while providing appropriate HTTP classification.
Parameters:
- e: The ErrorCodeName to use when errors of the target types are encountered
- targets: One or more type instances representing the types to map
Type Instance Format: Pass instances of the types you want to match, not reflect.Type objects:
// Concrete types
codeMap.MapErrorTypes(errors.InvalidArgument,
MyValidationError{}, // Value type
&MyBusinessError{}) // Pointer type
// Interface types (use typed nil)
codeMap.MapErrorTypes(errors.Unauthenticated,
(*AuthError)(nil)) // Interface type
Example usage:
// Custom application error types
codeMap.MapErrorTypes(errors.InvalidArgument,
ValidationError{}, // Custom validation errors
BusinessRuleError{}) // Business logic violations
// Third-party library error types
codeMap.MapErrorTypes(errors.Internal,
&pq.Error{}, // PostgreSQL driver errors
&json.SyntaxError{}, // JSON parsing errors
&url.Error{}) // URL parsing errors
// Interface-based error handling
codeMap.MapErrorTypes(errors.RequestTimeout,
(*TimeoutError)(nil), // Any error implementing TimeoutError
context.DeadlineExceeded) // Context timeouts
Advanced Type Matching: The type matching system supports sophisticated error hierarchies:
// Base error interface
type DomainError interface {
error
Domain() string
}
// Specific implementations
type UserError struct { /* ... */ }
func (e UserError) Domain() string { return "user" }
type PaymentError struct { /* ... */ }
func (e PaymentError) Domain() string { return "payment" }
// Map the interface to catch all domain errors
codeMap.MapErrorTypes(errors.InvalidArgument, (*DomainError)(nil))
Thread Safety: This method must be called during application initialization before the HTTP server starts, as it modifies internal mapping structures.
See MapErrorTypesTransformed() for cases where you want to return the typed error instance rather than the original error.
func (ErrorCodeMap) MapErrorTypesTransformed ¶
func (m ErrorCodeMap) MapErrorTypesTransformed(e ErrorCodeName, targets ...any) ErrorCodeMap
MapErrorTypesTransformed registers error types that should be mapped to a particular ErrorCodeName, but returns the typed error instance rather than the original error. This method is useful when you want to normalize error types or extract specific error instances from error chains for consistent handling.
Unlike MapErrorTypes() which returns the original error unchanged, this method returns the specific typed error instance that matched, potentially extracted from an error chain. This enables error normalization and type-specific processing.
Parameters:
- e: The ErrorCodeName to use when errors of the target types are encountered
- targets: One or more type instances representing the types to map and extract
Transformation Behavior: When an error chain contains multiple wrapped errors and one matches the target type, this method extracts and returns the matching typed error instance rather than the full wrapped error. This can be useful for standardizing error formats.
Example usage:
// Extract specific validation errors from chains
codeMap.MapErrorTypesTransformed(errors.InvalidArgument, ValidationError{})
// Input: fmt.Errorf("user creation failed: %w", ValidationError{Field: "email"})
// Output: ValidationError{Field: "email"} (extracted from chain)
// Normalize database errors
codeMap.MapErrorTypesTransformed(errors.Internal, &sql.Error{})
// Input: fmt.Errorf("database operation failed: %w", &sql.Error{Code: "23505"})
// Output: &sql.Error{Code: "23505"} (extracted and normalized)
// Extract timeout errors for consistent handling
codeMap.MapErrorTypesTransformed(errors.RequestTimeout, (*TimeoutError)(nil))
Use Cases: - Error normalization across different error sources - Extracting typed errors from complex error chains - Standardizing error formats for consistent client responses - Type-specific error processing and formatting - Removing wrapper context while preserving core error information
Comparison with MapErrorTypes(): - MapErrorTypes(): Returns original error, preserves full context - MapErrorTypesTransformed(): Returns typed instance, normalizes format
Thread Safety: This method must be called during application initialization before the HTTP server starts, as it modifies internal mapping structures.
Implementation Note: This method uses the same underlying type matching logic as MapErrorTypes() but with different return behavior for the transformation function.
func (ErrorCodeMap) MapErrors ¶
func (m ErrorCodeMap) MapErrors(e ErrorCodeName, targets ...error) ErrorCodeMap
MapErrors registers specific error instances that should be automatically mapped to a particular ErrorCodeName when encountered. This method provides exact error matching using errors.Is() semantics, making it ideal for mapping well-known errors from standard library packages or third-party dependencies.
Error matching uses errors.Is(), which means: - Exact error instances are matched - Wrapped errors containing the target error are matched - Error chains are traversed to find matches - Custom As() and Is() implementations are respected
When any of the target errors is encountered (directly or through wrapping), the original error is passed through unchanged with the specified ErrorCodeName. This preserves error context while providing appropriate HTTP classification.
Parameters:
- e: The ErrorCodeName to use when any of the target errors is encountered
- targets: One or more specific error instances to map to this ErrorCodeName
Example usage:
// Standard library errors codeMap.MapErrors(errors.NotFound, sql.ErrNoRows, // Database: no results os.ErrNotExist) // File system: file not found // Third-party library errors codeMap.MapErrors(errors.AlreadyExists, gorm.ErrDuplicateKey, // GORM: duplicate key violation mongo.ErrDuplicateKey) // MongoDB: duplicate key // Custom application errors codeMap.MapErrors(errors.PermissionDenied, auth.ErrInsufficientPermissions, auth.ErrTokenExpired, auth.ErrAccountSuspended) // Network and connectivity errors codeMap.MapErrors(errors.Unavailable, redis.ErrPoolExhausted, kafka.ErrBrokerNotAvailable)
Implementation Details: This method internally creates a transformation function that iterates through the target errors and uses errors.Is() to check for matches. The first match returns the original error, while no matches return nil to allow other mappings.
Thread Safety: This method must be called during application initialization before the HTTP server starts, as it modifies internal mapping structures.
type ErrorCodeName ¶
type ErrorCodeName string
ErrorCodeName represents a canonical error identifier that maps to an HTTP status code. It serves as a type-safe way to reference specific error types throughout your application while providing methods for generating structured error responses.
ErrorCodeName instances are typically created during application initialization using the Register function and then used throughout the application to send consistent error responses to clients.
Key characteristics: - Type-safe error identification - Automatic HTTP status code mapping - Multiple response formatting options (Message, Detail, Problem, etc.) - Integration with logging and error collection systems - Support for validation errors and custom data
Example usage:
var UserNotFound = errors.Register("USER_NOT_FOUND", http.StatusNotFound)
// In handler:
UserNotFound.Detail(ctx, "user not found", "user with ID %s does not exist", userID)
Available methods include Message, Detail, Problem, Data, Validation, Err, Log, and LogErr. Each method provides different levels of detail and formatting options for error responses.
var ( // InvalidArgument indicates that the client specified an invalid argument. InvalidArgument ErrorCodeName = Register("INVALID_ARGUMENT", http.StatusBadRequest) // FailedPrecondition indicates that the operation was rejected because the system is not in a state required for the operation's execution. FailedPrecondition ErrorCodeName = Register("FAILED_PRECONDITION", http.StatusBadRequest) // OutOfRange indicates that an operation was attempted past the valid range. OutOfRange ErrorCodeName = Register("OUT_OF_RANGE", http.StatusBadRequest) // UnsupportedMediaType indicates that the request entity has a media type which the server or resource does not support. UnsupportedMediaType ErrorCodeName = Register("UNSUPPORTED_MEDIA_TYPE", http.StatusUnsupportedMediaType) // DeadlineExceeded indicates that the deadline expired before the operation could complete. DeadlineExceeded ErrorCodeName = Register("DEADLINE_EXCEEDED", http.StatusGatewayTimeout) // NotFound indicates that the requested resource could not be found. NotFound ErrorCodeName = Register("NOT_FOUND", http.StatusNotFound) // MethodNotAllowed indicates that the HTTP method used is not supported by the resource. MethodNotAllowed ErrorCodeName = Register("METHOD_NOT_ALLOWED", http.StatusMethodNotAllowed) // AlreadyExists indicates that the resource that a client tried to create already exists. AlreadyExists ErrorCodeName = Register("ALREADY_EXISTS", http.StatusConflict) // Aborted indicates that the operation was aborted, typically due to a concurrency issue. Aborted ErrorCodeName = Register("ABORTED", http.StatusConflict) // PermissionDenied indicates that the caller does not have permission to execute the specified operation. PermissionDenied ErrorCodeName = Register("PERMISSION_DENIED", http.StatusForbidden) // Unauthenticated indicates that the request does not have valid authentication credentials for the operation. Unauthenticated ErrorCodeName = Register("UNAUTHENTICATED", http.StatusUnauthorized) // ResourceExhausted indicates that some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. ResourceExhausted ErrorCodeName = Register("RESOURCE_EXHAUSTED", http.StatusTooManyRequests) // TooLarge indicates that the request entity is larger than limits defined by server. TooLarge ErrorCodeName = Register("TOO_LARGE", http.StatusRequestEntityTooLarge) // Unimplemented indicates that the operation is not implemented or not supported/enabled in this service. Unimplemented ErrorCodeName = Register("UNIMPLEMENTED", http.StatusNotImplemented) Unavailable ErrorCodeName = Register("UNAVAILABLE", http.StatusServiceUnavailable) // BadGateway indicates that an upstream this service depends on failed. // // It is distinct from Unavailable, which says this service cannot serve the // request. Any proxy or gateway needs the difference, and the set had 503 and // 504 without it. BadGateway ErrorCodeName = Register("BAD_GATEWAY", http.StatusBadGateway) // Internal indicates an internal server error. Internal ErrorCodeName = Register("INTERNAL", http.StatusInternalServerError) // DataLoss indicates unrecoverable data loss or corruption. DataLoss ErrorCodeName = Register("DATA_LOSS", http.StatusInternalServerError) // Unknown indicates an unknown error. Unknown ErrorCodeName = Register("UNKNOWN", http.StatusInternalServerError) // PaymentRequired indicates that payment is required to access the resource. PaymentRequired ErrorCodeName = Register("PAYMENT_REQUIRED", http.StatusPaymentRequired) // NotAcceptable indicates that the resource is not capable of generating content acceptable according to the Accept headers sent in the request. NotAcceptable ErrorCodeName = Register("NOT_ACCEPTABLE", http.StatusNotAcceptable) // ProxyAuthRequired indicates that the client must first authenticate itself with the proxy. ProxyAuthRequired ErrorCodeName = Register("PROXY_AUTH_REQUIRED", http.StatusProxyAuthRequired) // RequestTimeout indicates that the server timed out waiting for the request. RequestTimeout ErrorCodeName = Register("REQUEST_TIMEOUT", http.StatusRequestTimeout) // Cancelled indicates that the operation was cancelled, typically by the // caller (gRPC CANCELLED). // // The status is 408 Request Timeout, the closest standard status for "the // client stopped waiting". The non-standard 499 that nginx logs for a // client-closed request is already taken by TokenRequired // (context.StatusTokenRequired) and stays there. Cancelled ErrorCodeName = Register("CANCELLED", http.StatusRequestTimeout) // Gone indicates that the resource requested is no longer available and will not be available again. Gone ErrorCodeName = Register("GONE", http.StatusGone) // LengthRequired indicates that the request did not specify the length of its content, which is required by the requested resource. LengthRequired ErrorCodeName = Register("LENGTH_REQUIRED", http.StatusLengthRequired) // PreconditionFailed indicates that the server does not meet one of the preconditions that the requester put on the request. PreconditionFailed ErrorCodeName = Register("PRECONDITION_FAILED", http.StatusPreconditionFailed) // RequestURITooLong indicates that the URI provided was too long for the server to process. RequestURITooLong ErrorCodeName = Register("REQUEST_URI_TOO_LONG", http.StatusRequestURITooLong) // RequestedRangeNotSatisfiable indicates that the server cannot supply the portion of the file requested. RequestedRangeNotSatisfiable ErrorCodeName = Register("REQUESTED_RANGE_NOT_SATISFIABLE", http.StatusRequestedRangeNotSatisfiable) // ExpectationFailed indicates that the server cannot meet the requirements of the Expect request-header field. ExpectationFailed ErrorCodeName = Register("EXPECTATION_FAILED", http.StatusExpectationFailed) // ImATeapot indicates that the server refuses to brew coffee because it is, permanently, a teapot. ImATeapot ErrorCodeName = Register("IM_A_TEAPOT", http.StatusTeapot) // MisdirectedRequest indicates that the request was directed at a server that is not able to produce a response. MisdirectedRequest ErrorCodeName = Register("MISDIRECTED_REQUEST", http.StatusMisdirectedRequest) // UnprocessableEntity indicates that the server understands the content type of the request entity, but was unable to process the contained instructions. UnprocessableEntity ErrorCodeName = Register("UNPROCESSABLE_ENTITY", http.StatusUnprocessableEntity) // Locked indicates that the resource that is being accessed is locked. Locked ErrorCodeName = Register("LOCKED", http.StatusLocked) // FailedDependency indicates that the request failed due to failure of a previous request. FailedDependency ErrorCodeName = Register("FAILED_DEPENDENCY", http.StatusFailedDependency) // TooEarly indicates that the server is unwilling to risk processing a request that might be replayed. TooEarly ErrorCodeName = Register("TOO_EARLY", http.StatusTooEarly) // UpgradeRequired indicates that the client should switch to a different protocol. UpgradeRequired ErrorCodeName = Register("UPGRADE_REQUIRED", http.StatusUpgradeRequired) // PreconditionRequired indicates that the origin server requires the request to be conditional. PreconditionRequired ErrorCodeName = Register("PRECONDITION_REQUIRED", http.StatusPreconditionRequired) // RequestHeaderFieldsTooLarge indicates that the server is unwilling to process the request because its header fields are too large. RequestHeaderFieldsTooLarge ErrorCodeName = Register("REQUEST_HEADER_FIELDS_TOO_LARGE", http.StatusRequestHeaderFieldsTooLarge) UnavailableForLegalReasons ErrorCodeName = Register("UNAVAILABLE_FOR_LEGAL_REASONS", http.StatusUnavailableForLegalReasons) // HTTPVersionNotSupported indicates that the server does not support the HTTP protocol version used in the request. HTTPVersionNotSupported ErrorCodeName = Register("HTTP_VERSION_NOT_SUPPORTED", http.StatusHTTPVersionNotSupported) // VariantAlsoNegotiates indicates that the server has an internal configuration error. VariantAlsoNegotiates ErrorCodeName = Register("VARIANT_ALSO_NEGOTIATES", http.StatusVariantAlsoNegotiates) // InsufficientStorage indicates that the server is unable to store the representation needed to complete the request. InsufficientStorage ErrorCodeName = Register("INSUFFICIENT_STORAGE", http.StatusInsufficientStorage) // LoopDetected indicates that the server detected an infinite loop while processing a request. LoopDetected ErrorCodeName = Register("LOOP_DETECTED", http.StatusLoopDetected) // NotExtended indicates that further extensions to the request are required for the server to fulfill it. NotExtended ErrorCodeName = Register("NOT_EXTENDED", http.StatusNotExtended) // NetworkAuthenticationRequired indicates that the client needs to authenticate to gain network access. NetworkAuthenticationRequired ErrorCodeName = Register("NETWORK_AUTHENTICATION_REQUIRED", http.StatusNetworkAuthenticationRequired) // PageExpired indicates that the page has expired. PageExpired ErrorCodeName = Register("PAGE_EXPIRED", context.StatusPageExpired) // BlockedByWindowsParentalControls indicates that the request was blocked by Windows Parental Controls. BlockedByWindowsParentalControls ErrorCodeName = Register("BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS", context.StatusBlockedByWindowsParentalControls) // InvalidToken indicates that the token provided is invalid. InvalidToken ErrorCodeName = Register("INVALID_TOKEN", context.StatusInvalidToken) // TokenRequired indicates that a token is required to access the resource. TokenRequired ErrorCodeName = Register("TOKEN_REQUIRED", context.StatusTokenRequired) // BandwidthLimitExceeded indicates that the bandwidth limit has been exceeded. BandwidthLimitExceeded ErrorCodeName = Register("BANDWIDTH_LIMIT_EXCEEDED", context.StatusBandwidthLimitExceeded) // InvalidSSLCertificate indicates that the SSL certificate is invalid. InvalidSSLCertificate ErrorCodeName = Register("INVALID_SSL_CERTIFICATE", context.StatusInvalidSSLCertificate) // SiteOverloaded indicates that the site is overloaded. SiteOverloaded ErrorCodeName = Register("SITE_OVERLOADED", context.StatusSiteOverloaded) // SiteFrozen indicates that the site is frozen. SiteFrozen ErrorCodeName = Register("SITE_FROZEN", context.StatusSiteFrozen) // NetworkReadTimeout indicates that there was a network read timeout error. NetworkReadTimeout ErrorCodeName = Register("NETWORK_READ_TIMEOUT", context.StatusNetworkReadTimeout) )
List of default error codes a server should follow and send back to the client.
Known error code names: - InvalidArgument - FailedPrecondition - OutOfRange - UnsupportedMediaType - DeadlineExceeded - NotFound - MethodNotAllowed - AlreadyExists - Aborted - PermissionDenied - Unauthenticated - ResourceExhausted - TooLarge - Unimplemented - Unavailable - BadGateway - Internal - DataLoss - Unknown - PaymentRequired - NotAcceptable - ProxyAuthRequired - RequestTimeout - Cancelled - Gone - LengthRequired - PreconditionFailed - RequestURITooLong - RequestedRangeNotSatisfiable - ExpectationFailed - ImATeapot - MisdirectedRequest - UnprocessableEntity - Locked - FailedDependency - TooEarly - UpgradeRequired - PreconditionRequired - RequestHeaderFieldsTooLarge - UnavailableForLegalReasons - HTTPVersionNotSupported - VariantAlsoNegotiates - InsufficientStorage - LoopDetected - NotExtended - NetworkAuthenticationRequired - PageExpired - BlockedByWindowsParentalControls - InvalidToken - TokenRequired - BandwidthLimitExceeded - InvalidSSLCertificate - SiteOverloaded - SiteFrozen - NetworkReadTimeout
func Register ¶
func Register(httpErrorCanonicalName string, httpStatusCode int) ErrorCodeName
Register creates and registers a new canonical error name with its associated HTTP status code, returning an ErrorCodeName that can be used throughout the application for consistent error handling.
This function should be called during application initialization (typically in package init() functions or early in main()) to register all custom error types before the HTTP server starts. The internal error registry is not protected by mutex for performance reasons.
Parameters:
- httpErrorCanonicalName: A descriptive, uppercase string identifier for the error type. Convention suggests using UPPER_SNAKE_CASE format (e.g., "USER_NOT_FOUND", "INVALID_CREDENTIALS").
- httpStatusCode: The HTTP status code that should be returned when this error occurs.
Returns:
- ErrorCodeName: A typed identifier that can be used to generate error responses.
Example usage:
var (
UserNotFound = errors.Register("USER_NOT_FOUND", http.StatusNotFound)
InvalidEmail = errors.Register("INVALID_EMAIL", http.StatusBadRequest)
PaymentRequired = errors.Register("PAYMENT_REQUIRED", http.StatusPaymentRequired)
)
// Later in handlers:
func getUser(ctx iris.Context) {
if user == nil {
UserNotFound.Detail(ctx, "user not found", "user with ID %s does not exist", userID)
return
}
}
See also RegisterErrorCode and RegisterErrorCodeMap for alternative registration methods.
Thread Safety: This function must be called before the HTTP server starts and is not thread-safe. Calling this after server startup may result in undefined behavior.
func (ErrorCodeName) Data ¶
func (e ErrorCodeName) Data(ctx *context.Context, msg string, data any)
Data sends an HTTP error response with a message and additional structured data. This method is useful when you need to include extra information beyond the basic error message, such as validation details, suggested actions, or context-specific data.
The data parameter can be any value that can be marshaled to JSON, including structs, maps, slices, or primitive values. The data will be included in the "data" field of the JSON error response.
Parameters:
- ctx: The Iris request context for the current HTTP request
- msg: The primary error message to send to the client
- data: Additional structured data to include in the error response
Example usage:
// Simple data
errors.InvalidArgument.Data(ctx, "validation failed", map[string]string{
"field": "email",
"requirement": "valid email format",
})
// Complex structured data
errors.NotFound.Data(ctx, "resource not found", struct {
ResourceType string `json:"resource_type"`
SearchCriteria []string `json:"search_criteria"`
Suggestions []string `json:"suggestions"`
}{
ResourceType: "user",
SearchCriteria: []string{"id:123", "email:user@example.com"},
Suggestions: []string{"check user ID", "verify email spelling"},
})
Response example (JSON):
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INVALID_ARGUMENT",
"status": 400
},
"message": "validation failed",
"data": {
"field": "email",
"requirement": "valid email format"
}
}
This method immediately stops request processing and sends the response. See also DataWithDetail() for including both detail and data fields.
func (ErrorCodeName) DataWithDetail ¶
func (e ErrorCodeName) DataWithDetail(ctx *context.Context, msg, detail string, data any)
DataWithDetail sends an HTTP error response with a message, detail, and additional structured data. It combines Detail() and Data(), so one call carries both the explanation and the structured supplementary information.
This is particularly useful for complex error scenarios where you need to provide both human-readable explanations and machine-readable data for client processing.
Parameters:
- ctx: The Iris request context for the current HTTP request
- msg: The primary error message - a concise summary of what went wrong
- detail: Additional detailed information about the error
- data: Additional structured data to include in the error response
Example usage:
errors.InvalidArgument.DataWithDetail(ctx,
"validation failed",
"multiple fields contain invalid values",
map[string]any{
"invalid_fields": []string{"email", "phone", "age"},
"valid_examples": map[string]string{
"email": "user@example.com",
"phone": "+1-555-123-4567",
"age": "21",
},
})
Response example (JSON):
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INVALID_ARGUMENT",
"status": 400
},
"message": "validation failed",
"detail": "multiple fields contain invalid values",
"data": {
"invalid_fields": ["email", "phone", "age"],
"valid_examples": {
"email": "user@example.com",
"phone": "+1-555-123-4567",
"age": "21"
}
}
}
This method immediately stops request processing and sends the response.
func (ErrorCodeName) DenySort ¶
func (e ErrorCodeName) DenySort(message string) context.PaginationOption
DenySort rejects any sort request with this error code and the given message. It is the context.DenySort pagination option answered with a chosen status instead of the default 400 Bad Request.
Use it where sorting is a permission and not a shape: a list a customer may read but not order answers 403, and the client can tell the two apart.
Usage:
list, filter, ok := ctx.BindPagination[customer.CheatFoodFilterOptions](
errors.PermissionDenied.DenySort("sort feature is not available for customers"))
if !ok {
return
}
func (ErrorCodeName) Detail ¶
func (e ErrorCodeName) Detail(ctx *context.Context, msg, detail string)
Detail sends an HTTP error response with both a main message and additional detail information. This method is ideal when you need to provide both a concise error summary and more specific information about what went wrong, helping clients understand both what happened and why.
The detail field provides additional context that can be useful for debugging, user guidance, or programmatic error handling by client applications.
Parameters:
- ctx: The Iris request context for the current HTTP request
- msg: The primary error message - a concise summary of what went wrong
- detail: Additional detailed information about the error, its cause, or resolution steps
Example usage:
errors.InvalidArgument.Detail(ctx, "validation failed", "email field contains an invalid email address") errors.NotFound.Detail(ctx, "resource not found", "user with ID 'user123' does not exist in the system") errors.PermissionDenied.Detail(ctx, "access denied", "user lacks the 'admin' role required for this operation")
Response example (JSON):
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INVALID_ARGUMENT",
"status": 400
},
"message": "validation failed",
"detail": "email field contains an invalid email address"
}
This method immediately stops request processing and sends the response.
See also Message() for simple messages, and Problem() for RFC 7807 problem details format.
func (ErrorCodeName) Detailf ¶
func (e ErrorCodeName) Detailf(ctx *context.Context, msg, detail string, detailArgs ...any)
Detailf sends an HTTP error response with a main message and a formatted detail string, providing a convenient way to include dynamic values in the detailed error information.
This method combines the structured approach of Detail() with the formatting convenience of printf-style string formatting for the detail field.
Parameters:
- ctx: The Iris request context for the current HTTP request
- msg: The primary error message - a concise summary of what went wrong
- detail: The format string for the detailed error information (printf-style)
- detailArgs: Arguments to be formatted into the detail string
Example usage:
errors.InvalidArgument.Detailf(ctx, "validation failed", "field %q has length %d but must be between %d and %d characters", fieldName, actualLength, minLength, maxLength) errors.NotFound.Detailf(ctx, "user not found", "user with ID %s was not found in organization %s", userID, orgID) errors.TooLarge.Detailf(ctx, "file too large", "uploaded file size %d MB exceeds limit of %d MB", actualMB, limitMB)
Response example (JSON):
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INVALID_ARGUMENT",
"status": 400
},
"message": "validation failed",
"detail": "field \"email\" has length 5 but must be between 10 and 100 characters"
}
This method immediately stops request processing and sends the response.
func (ErrorCodeName) Err ¶
func (e ErrorCodeName) Err(ctx *context.Context, err error)
Err sends an HTTP error response using the error's message text as the client-visible message. This method provides automatic error type detection and intelligent handling of different error scenarios, making it ideal for generic error processing where you want to expose the actual error message to clients.
The method performs several automatic behaviors: - Validation errors are automatically routed to the Validation() method for structured handling - ValidationErrors (multiple validation failures) are handled collectively - Existing Error struct instances are sent directly with the current error code - Nested errors with data are automatically extracted and included in the response - Private errors (context.ErrPrivate) trigger server-side logging while sending generic messages
Error Processing Features: - Automatic detail extraction from errors implementing detailedError interface - JSON data extraction from struct-type errors for rich error responses - Proper handling of wrapped and joined errors with data preservation - Security-conscious private error handling that protects sensitive information
Parameters:
- ctx: The Iris request context for the current HTTP request
- err: The error to be processed and sent to the client (can be nil)
Example usage:
// Simple error forwarding
if err := userService.GetUser(userID); err != nil {
errors.NotFound.Err(ctx, err) // Uses err.Error() as message
return
}
// Automatic validation error handling
if err := validation.ValidateEmail(email); err != nil {
errors.InvalidArgument.Err(ctx, err) // Automatically uses Validation() method
return
}
// Complex error with embedded data
type UserError struct {
UserID string `json:"user_id"`
Reason string `json:"reason"`
Attempts int `json:"attempts"`
}
userErr := &UserError{UserID: "123", Reason: "invalid credentials", Attempts: 3}
errors.Unauthenticated.Err(ctx, userErr) // Data automatically extracted
Response example (JSON) for simple error:
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "NOT_FOUND",
"status": 404
},
"message": "user not found"
}
Response example (JSON) for error with embedded data:
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "UNAUTHENTICATED",
"status": 401
},
"message": "invalid credentials",
"data": {
"user_id": "123",
"reason": "invalid credentials",
"attempts": 3
}
}
Security Note: This method exposes the actual error message to clients. Use ErrPrivate() when the error might contain sensitive information that should not be exposed to clients.
This method immediately stops request processing and sends the response. Use Wrap() instead if you need to return errors from functions for later processing.
See ErrPrivate() for security-conscious error handling that hides sensitive details.
func (ErrorCodeName) ErrPrivate ¶
func (e ErrorCodeName) ErrPrivate(ctx *context.Context, err error)
ErrPrivate sends an HTTP error response with a generic message to the client while logging the full error details server-side. This method is essential for security-conscious error handling where you need to prevent sensitive information from being exposed to clients.
This method is particularly important when dealing with: - Database errors that might contain schema information - Internal service errors with implementation details - Authentication errors with sensitive credential information - File system errors with server path information - Third-party service errors with internal details
The method performs the same intelligent error processing as Err() but ensures that only generic, safe messages are sent to clients while maintaining complete error information in server-side logs for debugging and monitoring.
That holds for every error type. A ValidationError and a *Error, which Err() renders as they are, get the generic message here as well.
Security Features: - Automatically logs full error details server-side for debugging - Sends only generic "server error" messages to clients - Preserves error context for internal monitoring and alerting - Prevents information leakage through error messages - Maintains error traceability for operational support
Parameters:
- ctx: The Iris request context for the current HTTP request
- err: The error to be logged and handled (can be nil)
Example usage:
// Database error with sensitive information
user, err := db.Query("SELECT * FROM users WHERE secret_token = ?", token)
if err != nil {
errors.Internal.ErrPrivate(ctx, err) // Logs full SQL error, sends generic message
return
}
// External service error with internal details
if err := paymentService.ProcessPayment(details); err != nil {
errors.Internal.ErrPrivate(ctx, err) // Hides payment provider internals
return
}
// File system error with server paths
if err := ioutil.ReadFile("/etc/app/config.json"); err != nil {
errors.Internal.ErrPrivate(ctx, err) // Hides server file structure
return
}
Response example (JSON) - client sees only generic message:
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INTERNAL",
"status": 500
},
"message": "server error",
"detail": "an unexpected error occurred while processing the request"
}
Server-side log will contain the full error details for debugging and monitoring.
Best Practices: - Use ErrPrivate() for any error that might contain sensitive information - Use Err() only when you're certain the error message is safe for client consumption - Consider using error mapping (Options.MapErrors) for automatic private error detection - Always log the full error server-side when using private error handling
This method immediately stops request processing and sends the response.
func (ErrorCodeName) Error ¶
func (e ErrorCodeName) Error() string
Error implements the error interface for ErrorCodeName, returning an empty string. This method exists solely to make ErrorCodeName compatible with Go's error interface, enabling it to be used in error wrapping and joining operations.
The empty string return is intentional - ErrorCodeName serves as a tag/marker in error chains rather than contributing descriptive text. The actual error messages are provided through the various response methods (Message, Detail, etc.).
Usage in error wrapping:
err = errors.InvalidArgument.Wrap(originalErr)
// or
err = fmt.Errorf("validation failed: %w", errors.InvalidArgument)
This allows error handling code to detect specific error types:
var argErr errors.ErrorCodeName
if errors.As(err, &argErr) {
// Handle specific error code
}
func (ErrorCodeName) Handle ¶
func (e ErrorCodeName) Handle(ctx *context.Context, err error) bool
Handle renders "err" as this error code and reports whether it did, so a fallible step is one guarded line:
if errors.Unavailable.Handle(ctx, api.users.UpdateEmail(ctx, old, new)) {
return
}
A nil error writes nothing and reports false, so the handler continues.
It is the code-forcing counterpart of the package-level HandleError, which maps the error through the registry and answers 500 for one it does not recognise; Handle states the code at the call site instead, for a step whose failure means one thing there and nothing in general (a third-party call that is Unavailable, say).
Handle is Err plus the answer to "did it fire". Err stays as it is: its signature matches LogErrorFunc and cors.HandleErrorFunc, so errors.FailedPrecondition.Err is passed to them as a bare method value, and a return value would take that away.
func (ErrorCodeName) Log ¶
func (e ErrorCodeName) Log(ctx *context.Context, format string, args ...any)
Log creates a formatted error message and handles it through the configured logging and error processing pipeline. This method is designed for scenarios where you need to log specific formatted messages while potentially sending appropriate error responses to clients.
The method automatically handles cancellation detection, error logging, and client response generation. For Internal error codes, it sends generic messages to clients while logging the full details server-side for security purposes.
Cancellation Handling: The method respects the global SkipCanceled setting and returns early only when the client's own request context is canceled (ctx.IsCanceled()), so nothing is logged or written for a caller that is no longer listening.
The shape of the error does not get to decide that, and neither does the shape of an argument. An upstream dial or read timeout is a net.Error whose Timeout() is true and it satisfies errors.Is(err, context.DeadlineExceeded) too, yet it is the failure the client is waiting to hear about and the one an operator most needs to see. See Report, which follows the same rule.
Parameters:
- ctx: The Iris request context for the current HTTP request
- format: Printf-style format string for the error message
- args: Arguments to be formatted into the error message
Example usage:
// Simple formatted logging
errors.Internal.Log(ctx, "failed to process user %s: operation timeout", userID)
// Complex error with multiple values
errors.InvalidArgument.Log(ctx,
"validation failed for field %s: value %v is not in range [%d, %d]",
fieldName, fieldValue, minValue, maxValue)
// Database operation error
errors.Internal.Log(ctx, "database query failed for table %s: %v", tableName, dbErr)
// Performance monitoring
if processingTime > threshold {
errors.Internal.Log(ctx, "slow operation detected: %s took %v (threshold: %v)",
operation, processingTime, threshold)
}
Behavior by Error Code: - Internal errors: Logs full details server-side, sends generic message to client - Other error codes: Logs and sends the formatted message to the client
Response example (JSON) for Internal error code:
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INTERNAL",
"status": 500
},
"message": "server error",
"detail": "an unexpected error occurred while processing the request"
}
Server-side log will contain: "failed to process user user123: operation timeout"
Response example (JSON) for other error codes:
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INVALID_ARGUMENT",
"status": 400
},
"message": "validation failed for field email: value invalid@domain is not in range [10, 100]"
}
This method immediately stops request processing and sends the response unless the operation is canceled or the context is already stopped.
See LogErr() for logging existing error instances, and ErrPrivate() for always private logging.
func (ErrorCodeName) LogErr ¶
func (e ErrorCodeName) LogErr(ctx *context.Context, err error)
LogErr logs an existing error through the configured logging and error processing pipeline while handling appropriate client responses. This method is the primary way to log errors that have already been created while ensuring proper error handling and client communication.
The method provides automatic cancellation detection, server-side logging, and intelligent client response generation. For Internal error codes, it maintains security by sending generic messages to clients while preserving full error details in server-side logs.
Key Features: - Automatic cancellation detection and handling - Intelligent error processing through the configured error handling pipeline - Security-conscious client response generation - Integration with custom logging and error collection systems - Proper error context preservation for debugging and monitoring
Cancellation Handling: The method respects the global SkipCanceled setting and automatically skips processing when encountering canceled contexts or canceled errors, preventing unnecessary overhead and log noise during client disconnections or timeouts.
Parameters:
- ctx: The Iris request context for the current HTTP request
- err: The error to be logged and processed (can be nil)
Example usage:
// Database operation error
user, err := userRepository.GetUser(userID)
if err != nil {
errors.Internal.LogErr(ctx, err) // Logs full error, sends generic response
return
}
// External service error
if err := paymentService.ProcessPayment(amount); err != nil {
errors.Internal.LogErr(ctx, err) // Protects sensitive payment details
return
}
// Validation error from business logic
if err := validateBusinessRules(request); err != nil {
errors.InvalidArgument.LogErr(ctx, err) // Shows validation details to client
return
}
// File system operation error
if err := os.WriteFile(filepath, data, 0644); err != nil {
errors.Internal.LogErr(ctx, err) // Hides server file system details
return
}
Behavior by Error Code: - Internal errors: Full error logged server-side, generic message sent to client - Other error codes: Error logged and original message sent to client (unless private)
Response example (JSON) for Internal error:
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INTERNAL",
"status": 500
},
"message": "server error",
"detail": "an unexpected error occurred while processing the request"
}
Server-side logs will contain the complete error details with stack trace and context information for debugging and operational monitoring.
Error Processing Pipeline: 1. Cancellation detection and early return if applicable 2. Error logging through configured logging infrastructure 3. Error collection for monitoring and alerting systems 4. Client response generation with appropriate security filtering 5. Request processing termination
This method immediately stops request processing and sends the response unless the operation is canceled or the context is already stopped.
See Log() for formatted error logging, and ErrPrivate() for explicit private error handling.
func (ErrorCodeName) Message ¶
func (e ErrorCodeName) Message(ctx *context.Context, message string)
Message sends an immediate HTTP error response to the client with the specified message and the error code's associated HTTP status code. This is the simplest method for sending error responses when you only need to provide a basic error message.
The response will be formatted according to the configured renderer (JSON by default) and will include the error code's canonical name and status code in the response structure.
Parameters:
- ctx: The Iris request context for the current HTTP request
- message: The human-readable error message to send to the client
Example usage:
errors.NotFound.Message(ctx, "user not found") errors.InvalidArgument.Message(ctx, "email address is required") errors.Internal.Message(ctx, "service temporarily unavailable")
Response example (JSON):
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "NOT_FOUND",
"status": 404
},
"message": "user not found"
}
This method immediately stops request processing and sends the response. Use Wrap() instead if you need to return errors from functions for later processing.
See also Detail() for messages with additional details, and Problem() for RFC 7807 format.
func (ErrorCodeName) Messagef ¶
func (e ErrorCodeName) Messagef(ctx *context.Context, format string, args ...any)
Messagef sends an HTTP error response with a formatted message, providing a convenient way to include dynamic values in error messages without manual string formatting.
This method is equivalent to calling Message(ctx, fmt.Sprintf(format, args...)) but with optimized formatting that only calls fmt.Sprintf when arguments are provided.
Parameters:
- ctx: The Iris request context for the current HTTP request
- format: The format string for the error message (printf-style)
- args: Arguments to be formatted into the message
Example usage:
errors.NotFound.Messagef(ctx, "user with ID %s not found", userID) errors.InvalidArgument.Messagef(ctx, "field %q must be between %d and %d characters", fieldName, min, max) errors.TooLarge.Messagef(ctx, "file size %d bytes exceeds maximum of %d bytes", actualSize, maxSize)
Response example (JSON):
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "NOT_FOUND",
"status": 404
},
"message": "user with ID abc123 not found"
}
This method immediately stops request processing and sends the response.
func (ErrorCodeName) Problem ¶
func (e ErrorCodeName) Problem(ctx *context.Context, title, detail, typeURI, instanceURI string, extra ...any)
Problem sends an RFC 7807 compliant "Problem Details for HTTP APIs" error response. This method creates structured error responses that follow the RFC 7807 standard, providing machine-readable error information that can be easily processed by clients.
RFC 7807 defines a standard format for HTTP error responses that includes: - type: A URI reference identifying the problem type - title: A short, human-readable summary of the problem type - status: The HTTP status code (automatically set from the ErrorCodeName) - detail: A human-readable explanation specific to this occurrence - instance: A URI reference identifying the specific occurrence
The response will be rendered as "application/problem+json" if no custom renderer is configured, otherwise it uses the configured renderer with problem details.
Parameters:
- ctx: The Iris request context for the current HTTP request
- title: A short, human-readable summary of the problem type
- detail: A human-readable explanation specific to this occurrence of the problem
- typeURI: A URI reference that identifies the problem type (e.g., "https://example.com/probs/out-of-credit")
- instanceURI: A URI reference that identifies the specific occurrence (e.g., "/account/kataras/msgs/1")
- extra: Optional additional data to include in the problem details
Example usage:
errors.InvalidArgument.Problem(ctx, "Validation Failed", "The email field contains an invalid email address", "https://example.com/problems/validation-failed", "/users/create")
Response example (application/problem+json):
{
"type": "https://example.com/problems/validation-failed",
"title": "Validation Failed",
"status": 400,
"detail": "The email field contains an invalid email address",
"instance": "/users/create"
}
Multiple extra values are combined into an array, single values are included directly. Nil values in extra are automatically filtered out.
This method immediately stops request processing and sends the response. See RFC 7807: https://datatracker.ietf.org/doc/html/rfc7807 for complete specification.
func (ErrorCodeName) Report ¶
func (e ErrorCodeName) Report(ctx *context.Context, err error) *Error
Report runs the error pipeline under this specific error code and returns the resulting Error without writing anything to the response.
Use it when the code is already known - a classified upstream failure, say - and the error-code map has nothing to add. See the package-level Report for what the pipeline does and why it is separate from rendering.
func (ErrorCodeName) String ¶
func (e ErrorCodeName) String() string
String returns the string representation of the ErrorCodeName, implementing the fmt.Stringer interface. This is primarily used for logging, debugging, and error message formatting.
Example output: "USER_NOT_FOUND", "INVALID_CREDENTIALS", "INTERNAL"
func (ErrorCodeName) Validation ¶
func (e ErrorCodeName) Validation(ctx *context.Context, validationErrors ...ValidationError)
Validation sends an HTTP error response specifically designed for handling multiple validation failures. This method is optimized for scenarios where you need to report multiple field-level validation errors simultaneously, providing structured feedback about all validation issues in a single response.
The method accepts multiple ValidationError implementations, each containing detailed information about specific validation failures including field names, invalid values, and validation rules that were violated, so a client can tell the user exactly what to correct in every form field or input parameter at once.
Parameters:
- ctx: The Iris request context for the current HTTP request
- validationErrors: One or more ValidationError implementations containing detailed validation failure information
Example usage:
// Single validation error
emailErr := &MyValidationError{
Field: "email",
Value: "invalid-email",
Tag: "email",
Message: "must be a valid email address",
}
errors.InvalidArgument.Validation(ctx, emailErr)
// Multiple validation errors
emailErr := &MyValidationError{Field: "email", Message: "must be a valid email address"}
phoneErr := &MyValidationError{Field: "phone", Message: "must be a valid phone number"}
ageErr := &MyValidationError{Field: "age", Message: "must be between 18 and 120"}
errors.InvalidArgument.Validation(ctx, emailErr, phoneErr, ageErr)
// Using validation package utilities
var validationErrors []ValidationError
if err := validation.ValidateEmail(email); err != nil {
validationErrors = append(validationErrors, err.(ValidationError))
}
if err := validation.ValidatePhone(phone); err != nil {
validationErrors = append(validationErrors, err.(ValidationError))
}
if len(validationErrors) > 0 {
errors.InvalidArgument.Validation(ctx, validationErrors...)
}
Response example (JSON) for single validation error:
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INVALID_ARGUMENT",
"status": 400
},
"message": "validation failure",
"detail": "fields were invalid",
"validation": {
"field": "email",
"value": "invalid-email",
"tag": "email",
"message": "must be a valid email address"
}
}
Response example (JSON) for multiple validation errors:
{
"id": "req-123456",
"http_error_code": {
"canonical_name": "INVALID_ARGUMENT",
"status": 400
},
"message": "validation failure",
"detail": "fields were invalid",
"validation": [
{
"field": "email",
"message": "must be a valid email address"
},
{
"field": "phone",
"message": "must be a valid phone number"
},
{
"field": "age",
"message": "must be between 18 and 120"
}
]
}
This method is particularly useful for:
- Form validation with multiple fields
- API parameter validation across multiple inputs
- Batch input validation scenarios
- Complex business rule validation
The validation errors will be included in the response under the "validation" field, allowing clients to programmatically handle validation failures and provide specific user feedback for each field that failed validation.
This method immediately stops request processing and sends the response.
func (ErrorCodeName) Wrap ¶
func (e ErrorCodeName) Wrap(err error) error
Wrap creates a new error by joining the ErrorCodeName with the provided error, enabling the HandleError function to automatically detect and process the error with the appropriate error code and HTTP status code.
This method is particularly useful when you want to tag an error with a specific error code without immediately sending a response to the client. The wrapped error can be returned from functions and later processed by HandleError or other error handling mechanisms.
Parameters:
- err: The original error to be wrapped with this error code
Returns:
- error: A joined error containing both the ErrorCodeName and the original error
Example usage:
func getUserFromDB(userID string) (*User, error) {
user, err := db.GetUser(userID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errors.NotFound.Wrap(err)
}
return nil, errors.Internal.Wrap(err)
}
return user, nil
}
// In handler:
func getUserHandler(ctx iris.Context) {
user, err := getUserFromDB(ctx.Params().Get("id"))
if err != nil {
errors.HandleError(ctx, err) // Automatically detects error code
return
}
ctx.JSON(user)
}
The wrapped error maintains the original error's information while adding error code metadata that can be detected during error processing.
See HandleError function for automatic error code detection and processing.
type ErrorResolver ¶
ErrorResolver inspects an error inside HandleError and reports whether it produced a client response. Resolvers run after the per-route Options code map and before the built-in classification, in registration order.
They are the integration point for datastore- or driver-specific error mapping without linking the driver into every application: see the pgerrors subpackage for the PostgreSQL (github.com/kataras/pg) mapping.
type Func ¶
Func defines a function signature for error-aware HTTP handlers that can return errors instead of manually handling them. This type enables a more functional programming style for HTTP handlers where error handling is automatically managed by the framework.
Functions of this type return errors that go through the error handling pipeline: mapping, transformation, logging and the client response. Individual handlers do not repeat that work.
Function Signature:
- Input: iris.Context - The Iris request context
- Output: error - Any error that occurred during request processing, or nil for success
Usage Examples:
// Simple handler function
func getUserByID(ctx iris.Context) error {
userID := ctx.Params().Get("id")
user, err := userService.GetUser(userID)
if err != nil {
return err // Automatically handled by framework
}
ctx.JSON(user)
return nil
}
// Register with automatic error handling
app.Get("/users/{id}", errors.FuncHandler(getUserByID))
// Database operation with automatic error mapping
func createUser(ctx iris.Context) error {
var user User
if err := ctx.ReadJSON(&user); err != nil {
return err // JSON parsing errors automatically handled
}
if err := userService.Create(user); err != nil {
return err // Database errors automatically mapped
}
ctx.StatusCode(201)
ctx.JSON(user)
return nil
}
Error Handling Benefits: - Automatic error mapping through configured Options - Consistent error response formatting - Built-in logging and monitoring integration - Security-conscious private error handling - Validation error processing
This type is particularly useful with FuncHandler, FuncHandlers, and FuncMiddleware functions that provide the automatic error handling infrastructure.
type IDGeneratorFunc ¶
IDGeneratorFunc defines the signature for functions that generate unique identifiers for error instances. These IDs are used for error tracking, correlation across systems, and debugging purposes.
The function receives the current request context, which can be used to derive IDs from existing request metadata or to access application-specific ID generation services.
ID Requirements: - Must be unique across all errors in the system - Should be easily searchable in logs and monitoring systems - Should maintain some correlation with the request context when possible
Implementation Examples:
// UUID-based generation (default behavior)
func uuidGenerator(ctx iris.Context) string {
return uuid.New().String()
}
// Request-ID based generation
func requestBasedGenerator(ctx iris.Context) string {
requestID := ctx.ID()
errorSeq := atomic.AddInt64(&errorCounter, 1)
return fmt.Sprintf("%s-err-%d", requestID, errorSeq)
}
// Timestamp-based generation
func timestampGenerator(ctx iris.Context) string {
return fmt.Sprintf("err-%d-%s", time.Now().UnixNano(),
randomString(8))
}
// External service integration
func serviceGenerator(ctx iris.Context) string {
return errorTrackingService.GenerateErrorID(ctx.ID())
}
The default implementation generates UUIDs. Custom generators can be configured via Options.SetIDGenerator() or Options.SetID() for static IDs.
type LogErrorFunc ¶
LogErrorFunc defines the signature for error logging functions used throughout the error handling system. These functions are responsible for recording errors in logs, external monitoring systems, or other persistence mechanisms. The function receives both the request context and the error to be logged.
The context provides access to request-specific information such as request ID, user information, request path, and other metadata that can be useful for error correlation and debugging.
Implementation Examples:
// Simple logging to application logger
func simpleLogger(ctx iris.Context, err error) {
ctx.Application().Logger().Error(err)
}
// Structured logging with request context
func structuredLogger(ctx iris.Context, err error) {
logger.Error("HTTP request error",
"error", err.Error(),
"request_id", ctx.ID(),
"path", ctx.Path(),
"method", ctx.Method(),
"user_id", ctx.Values().GetString("user_id"))
}
// External service logging (Sentry, LogRocket, etc.)
func sentryLogger(ctx iris.Context, err error) {
sentry.WithScope(func(scope *sentry.Scope) {
scope.SetTag("request_id", ctx.ID())
scope.SetContext("request", map[string]any{
"path": ctx.Path(),
"method": ctx.Method(),
})
sentry.CaptureException(err)
})
}
The default implementation logs to the application's configured logger. Custom implementations can be set globally via the LogError package variable or per-route via Options.SetLogger().
Thread Safety: Implementations should be thread-safe as they may be called concurrently from multiple goroutines handling different requests.
var LogError LogErrorFunc = func(ctx *context.Context, err error) { if ctx == nil { slog.Error(err.Error()) return } ctx.Application().Logger().Error(err) }
LogError is the default global error logging function used throughout the error handling system. This function serves as the fallback logger when no custom logger is configured via Options.SetLogger(). Modifying this variable affects all error logging globally across the application.
The default implementation: - Uses the structured logger (slog) when no context is available - Uses the application's configured logger when context is provided - Automatically extracts relevant information from the context for enhanced logging
Default Behavior: - Context available: Uses ctx.Application().Logger().Error(err) - No context: Uses slog.Error(err.Error())
Global Customization Example:
// Replace global logger with custom implementation
errors.LogError = func(ctx iris.Context, err error) {
if ctx == nil {
myLogger.Error("Context-less error", "error", err)
return
}
myLogger.Error("HTTP request error",
"error", err.Error(),
"request_id", ctx.ID(),
"path", ctx.Path(),
"method", ctx.Method(),
"user_agent", ctx.Header("User-Agent"))
}
For route-specific or group-specific logging configuration, use Options.SetLogger() instead of modifying this global variable.
Thread Safety: This variable should be modified during application initialization before the HTTP server starts. Concurrent modification during runtime is not safe.
type MapErrorFn ¶
MapErrorFn is the stored form of every error mapping function: it receives the request context (nil when Filter is called directly, outside a request) and the error to classify, returning the transformed error or nil when it does not handle it. Context-unaware functions registered through MapErrorFunc, MapErrors and MapErrorTypes are adapted to this form.
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options configures HTTP error handling behavior in Iris applications. It is a middleware builder that must be configured before request handlers, and it decides how errors are processed, logged, collected and rendered.
The Options struct enables: - Error mapping and transformation based on error types or patterns - Custom logging integration with external services - Error collection for monitoring and analytics - Custom response rendering (JSON, HTML, Problem+JSON, etc.) - Unique error ID generation for tracking and correlation
Configuration Workflow: 1. Create new Options instance with NewOptions() 2. Configure error mapping, logging, collection, and rendering 3. Apply the configuration using Handler() or HandlerWithError() 4. Register the middleware before your application handlers
Example Usage:
// Basic configuration with error mapping
opts := errors.NewOptions().
MapErrors(errors.NotFound, sql.ErrNoRows, myapp.ErrUserNotFound).
MapErrors(errors.InvalidArgument, myapp.ErrInvalidEmail).
SetLogger(customLogger).
SetCollector(monitoringCollector).
SetRenderer(errors.HTML)
// Apply to specific routes
userRoutes := app.Party("/users")
userRoutes.Use(opts.Handler())
// Apply globally
app.Use(opts.Handler())
Error Processing Pipeline: When an error occurs, the Options configuration determines: 1. Whether the error matches any registered mappings 2. How the error should be logged (custom logger vs default) 3. Whether the error should be collected for monitoring 4. How the error response should be rendered to the client 5. What unique ID should be assigned to the error
Thread Safety: Options instances should be configured during application initialization before the HTTP server starts, as the internal error mapping is not protected by mutex for performance reasons.
func NewOptions ¶
func NewOptions() *Options
NewOptions creates and returns a new Options instance for configuring HTTP error handling in Iris applications. This function initializes a configuration that can be customized using the fluent API methods before being applied as middleware.
The returned Options instance starts with the following defaults: - A default error code mapping, seeded by makeDefaultErrorCodeMap - Default UUID-based error ID generation - Default application logger for error logging - No custom error collection or rendering
The default mapping already answers sql.ErrNoRows with NotFound, the kataras/jwt errors with Unauthenticated, view.ErrNoEngine with Internal and an error text of "encoding/hex: invalid byte:" with InvalidArgument, without any MapErrors call of your own.
Configuration should be done during application initialization before the HTTP server starts, as the internal error mapping structures are not thread-safe.
Returns:
- *Options: A new Options instance ready for configuration
Example usage:
// Basic configuration
opts := errors.NewOptions()
// Fluent configuration with method chaining
opts := errors.NewOptions().
MapErrors(errors.NotFound, sql.ErrNoRows).
MapErrors(errors.InvalidArgument, myapp.ValidationError{}).
SetLogger(customLogger).
SetCollector(monitoringCollector).
SetRenderer(errors.Problem)
// Apply to application routes
app.Use(opts.Handler())
The Options instance must be applied as middleware using Handler() or HandlerWithError() before any route handlers that should benefit from the custom error handling configuration.
See the Options struct documentation for detailed configuration options and the Handler() method for middleware application.
func (*Options) ErrorCodeMap ¶
func (opts *Options) ErrorCodeMap() ErrorCodeMap
ErrorCodeMap returns the internal error code mapping configuration for direct access. This method provides read-only access to the configured error mappings, which can be useful for debugging, testing, or introspection of the current error handling setup.
The returned ErrorCodeMap contains all configured error transformations including: - Error type mappings (MapErrorTypes) - Specific error instance mappings (MapErrors) - Custom error transformation functions (MapErrorFunc)
Returns:
- ErrorCodeMap: The current error code mapping configuration
Example usage:
opts := errors.NewOptions().
MapErrors(errors.NotFound, sql.ErrNoRows).
MapErrors(errors.InvalidArgument, myapp.ValidationError{})
// Inspect current mappings
codeMap := opts.ErrorCodeMap()
fmt.Printf("Configured mappings: %d\n", len(codeMap))
// Test error mapping behavior
testErr := sql.ErrNoRows
if codeMap.handle(ctx, testErr) {
fmt.Println("Error would be handled by configured mappings")
}
Thread Safety: The returned map should be treated as read-only. Modifications should be made through the Options configuration methods rather than direct map manipulation.
See ErrorCodeMap type documentation for details on mapping functionality.
func (*Options) Handler ¶
Handler returns the middleware handler which should be registered to the Iris router. If nothing was set, then it returns nil.
func (*Options) HandlerWithError ¶
HandlerWithError returns the middleware handler which should be registered to the Iris errors router.
func (*Options) HasRenderer ¶
HasRenderer reports whether this Options instance has a custom error renderer configured. This method is useful for conditional logic and debugging to determine if custom rendering will be applied to error responses.
When HasRenderer returns false, the default JSON rendering will be used for error responses. When it returns true, the custom renderer configured via SetRenderer will be used.
Returns:
- bool: true if a custom renderer is configured, false if default JSON rendering will be used
Example usage:
opts := errors.NewOptions()
fmt.Println(opts.HasRenderer()) // false
opts.SetRenderer(errors.HTML)
fmt.Println(opts.HasRenderer()) // true
// Conditional rendering logic
if opts.HasRenderer() {
fmt.Println("Custom error rendering is configured")
} else {
fmt.Println("Using default JSON error rendering")
}
This method is primarily used internally by the error handling system to determine the appropriate rendering strategy, but can also be useful for testing and debugging.
func (*Options) MapErrorAs ¶
func (opts *Options) MapErrorAs[E error](code ErrorCodeName, render func(E) *Error) *Options
MapErrorAs registers a typed error mapping: an E is looked for anywhere in the error tree, as the standard errors.AsType does, and render turns the value found into the *Error to send. A nil render result means "not mine", so the next mapping gets a turn, exactly like MapErrorFunc returning nil.
It chains like every other mapping method, and E is inferred from render:
opts := errors.NewOptions().
MapErrors(errors.NotFound, sql.ErrNoRows).
MapErrorAs(errors.ResourceExhausted, func(e *QuotaError) *errors.Error {
return &errors.Error{
Message: "quota exceeded",
Detail: fmt.Sprintf("the limit is %d", e.Limit),
}
})
A nil render classifies without transforming, the same as MapErrorTypes. Then E has to be named, because there is nothing left to infer it from:
opts.MapErrorAs[*QuotaError](errors.ResourceExhausted, nil)
Prefer this over MapErrorContains whenever the error carries a type: the fields of E are available to the message and nothing depends on the wording of a driver's text.
func (*Options) MapErrorContains ¶
func (opts *Options) MapErrorContains(e ErrorCodeName, substr, message string) *Options
MapErrorContains registers a substring mapping: an error whose Error() text contains substr is answered with e and the given message, which replaces the original text. The match is case-sensitive.
This exists for the SQL and vendor errors which arrive as text only, a constraint violation reported by a driver that exposes no code for it being the usual case. A typed mapping is preferable wherever one is possible: prefer MapErrorAs, MapErrorTypes or MapErrors, because a driver is free to reword its text in the next release.
An empty message keeps the original error text. An empty substr registers nothing at all, rather than a mapping which matches every error: a missing constant is a mistake, and the safe reading of it is "map nothing".
The message replaces the text on the way out, so the driver's own words are gone before any collector sees them. When they are the only diagnostic there is, log the error first, as pgerrors does with errors.LogError, and map it after.
Usage:
opts.MapErrorContains(errors.InvalidArgument, "violates check constraint", "invalid value")
func (*Options) MapErrorFunc ¶
func (opts *Options) MapErrorFunc(e ErrorCodeName, fn func(error) error) *Options
MapErrorFunc registers a custom error transformation function that processes incoming errors and optionally transforms them before they are sent to clients. This method provides the most flexible error mapping capability, allowing complex error analysis and transformation logic.
The provided function receives an error and can: - Return the same error unchanged (pass-through) - Return a modified version of the error (transformation) - Return nil to indicate this function doesn't handle the error (fallback to other mappings) - Return a completely different error (replacement)
When multiple MapErrorFunc functions are registered for the same ErrorCodeName, they are executed in registration order until one returns a non-nil error. This enables layered error processing and fallback mechanisms.
Parameters:
- e: The ErrorCodeName that should be used when this function handles an error
- fn: The transformation function that processes incoming errors
Function Signature:
- Input: error - The original error to be processed
- Output: error - The processed error, or nil if this function doesn't handle it
Example usage:
// Database error transformation
opts.MapErrorFunc(errors.Internal, func(err error) error {
if strings.Contains(err.Error(), "connection refused") {
return errors.Private(err) // Hide connection details from clients
}
return nil // Let other mappings handle this error
})
// Validation error enhancement
opts.MapErrorFunc(errors.InvalidArgument, func(err error) error {
if validationErr, ok := err.(MyValidationError); ok {
// Add additional context
return fmt.Errorf("validation failed for %s: %w", validationErr.Field, err)
}
return nil
})
// External service error mapping
opts.MapErrorFunc(errors.Unavailable, func(err error) error {
if isExternalServiceError(err) {
return fmt.Errorf("external service temporarily unavailable")
}
return nil
})
Thread Safety: This method must be called during application initialization before the HTTP server starts, as the internal mapping structures are not thread-safe.
Returns: *Options for method chaining
func (*Options) MapErrorFuncCtx ¶
func (opts *Options) MapErrorFuncCtx(e ErrorCodeName, fn MapErrorFn) *Options
MapErrorFuncCtx registers a context-aware error transformation function: like MapErrorFunc, but the function also receives the request context, so the transformed error can carry request detail (path, user, values). The context is nil when the code map's Filter is called directly, outside a request.
opts.MapErrorFuncCtx(errors.NotFound, func(ctx *context.Context, err error) error {
if errors.Is(err, ErrPlanNotFound) {
return fmt.Errorf("%s: %w", ctx.Path(), err)
}
return nil
})
func (*Options) MapErrorTypes ¶
func (opts *Options) MapErrorTypes(e ErrorCodeName, targets ...any) *Options
MapErrorTypes registers error types that should be automatically mapped to a particular ErrorCodeName when encountered. This method provides type-based error matching using Go's type assertion and interface satisfaction, making it ideal for mapping custom error types and interface implementations.
The method accepts type instances (not Type objects) and uses reflection to determine if incoming errors are assignable to the registered types. This enables flexible error handling for custom error hierarchies and interface-based error designs.
Type Matching: - Uses type assertion for interface types - Uses type comparison for concrete types - Supports pointer and value type matching - Works with embedded error types
Parameters:
- e: The ErrorCodeName to use when errors of the target types are encountered
- targets: One or more type instances (value or pointer) representing the types to map
Example usage:
// Custom error types
opts.MapErrorTypes(errors.InvalidArgument,
myapp.ValidationError{}, // Value type
&myapp.BusinessRuleError{}) // Pointer type
// Interface-based error types
opts.MapErrorTypes(errors.Unauthenticated,
(*myapp.AuthError)(nil), // Interface type
myapp.TokenExpiredError{}) // Concrete implementation
// Third-party library error types
opts.MapErrorTypes(errors.Internal,
&pq.Error{}, // PostgreSQL driver errors
&json.SyntaxError{}, // JSON parsing errors
&url.Error{}) // URL errors
// Built-in error types
opts.MapErrorTypes(errors.RequestTimeout,
&net.OpError{}, // Network operation errors
context.DeadlineExceeded) // Context timeout errors
Interface Handling: When mapping interface types, pass a typed nil pointer:
// Correct way to map interface types opts.MapErrorTypes(errors.InvalidArgument, (*ValidationError)(nil)) // This will match any error that implements ValidationError interface
Polymorphism: Type mapping supports polymorphic error handling where different concrete types implementing the same interface can be mapped to different ErrorCodeNames based on their specific type.
Thread Safety: This method must be called during application initialization before the HTTP server starts, as the internal mapping structures are not thread-safe.
Returns: *Options for method chaining
func (*Options) MapErrors ¶
func (opts *Options) MapErrors(e ErrorCodeName, targets ...error) *Options
MapErrors registers specific error instances or error values that should be automatically mapped to a particular ErrorCodeName when encountered. This method provides exact error matching using errors.Is() semantics, making it ideal for mapping well-known errors from standard library or third-party packages.
When any of the registered target errors is encountered (either directly or through error wrapping), the associated ErrorCodeName will be used to generate the HTTP response. This enables automatic translation of internal errors to appropriate HTTP status codes.
Error Matching: The method uses errors.Is() for matching, which means: - Exact error instances are matched - Wrapped errors containing the target are matched - Error chains are traversed to find matches
Parameters:
- e: The ErrorCodeName to use when any of the target errors is encountered
- targets: One or more specific error instances to map to this ErrorCodeName
Example usage:
// Database errors opts.MapErrors(errors.NotFound, sql.ErrNoRows, gorm.ErrRecordNotFound) opts.MapErrors(errors.AlreadyExists, sql.ErrDuplicateKey) // File system errors opts.MapErrors(errors.NotFound, os.ErrNotExist) opts.MapErrors(errors.PermissionDenied, os.ErrPermission) // Custom application errors opts.MapErrors(errors.InvalidArgument, myapp.ErrInvalidEmail, myapp.ErrInvalidPassword, myapp.ErrInvalidUserData) // External service errors opts.MapErrors(errors.Unavailable, redis.ErrPoolExhausted, kafka.ErrBrokerNotAvailable)
Multiple Mappings: The same error can be mapped to different ErrorCodeNames in different contexts by using separate Options instances for different route groups.
Thread Safety: This method must be called during application initialization before the HTTP server starts, as the internal mapping structures are not thread-safe.
Returns: *Options for method chaining
func (*Options) SetCollector ¶
func (opts *Options) SetCollector(fn ContextErrorFunc) *Options
SetCollector configures a custom error collection function for monitoring, analytics, and external error tracking systems. The collector receives fully-constructed Error instances and can process them for various purposes without affecting the client response.
Error collection is called synchronously before the error response is sent to the client, so time-consuming operations should be performed in separate goroutines to avoid blocking request processing and degrading user experience.
Common Use Cases: - Sending errors to monitoring services (Datadog, New Relic, Prometheus) - Storing errors in databases for analysis and reporting - Triggering alerts based on error patterns or frequency - Building error dashboards and metrics - Feeding data to machine learning systems for anomaly detection - Creating audit trails for compliance and debugging
Parameters:
- fn: The collection function that processes Error instances
Collection Function Signature:
- Input: ctx (iris.Context) - The current request context
- Input: err (*Error) - The fully-constructed Error instance with all details
- Output: None (void function)
Example implementations:
// Basic monitoring integration
opts.SetCollector(func(ctx iris.Context, err *Error) {
go func() { // Non-blocking collection
monitoring.ReportError(monitoring.ErrorEvent{
ID: err.ID,
Code: string(err.ErrorCode.CanonicalName),
Status: err.ErrorCode.Status,
Message: err.Message,
Detail: err.Detail,
RequestID: ctx.ID(),
UserID: ctx.Values().GetString("user_id"),
Endpoint: ctx.Path(),
Method: ctx.Method(),
Timestamp: time.Now(),
UserAgent: ctx.Header("User-Agent"),
IPAddress: ctx.RemoteAddr(),
})
}()
})
// Database storage for analysis
opts.SetCollector(func(ctx iris.Context, err *Error) {
go func() { // Non-blocking storage
errorRecord := &ErrorRecord{
ID: err.ID,
ErrorCode: string(err.ErrorCode.CanonicalName),
HTTPStatus: err.ErrorCode.Status,
Message: err.Message,
Detail: err.Detail,
ValidationData: err.Validation,
RequestPath: ctx.Path(),
RequestMethod: ctx.Method(),
UserID: ctx.Values().GetString("user_id"),
CreatedAt: time.Now(),
}
database.InsertErrorRecord(errorRecord)
}()
})
// Alert triggering based on error patterns
opts.SetCollector(func(ctx iris.Context, err *Error) {
// Check for high-severity errors
if err.ErrorCode.Status >= 500 {
go alerting.TriggerAlert(alerting.Alert{
Severity: "high",
Message: fmt.Sprintf("Server error: %s", err.Message),
ErrorID: err.ID,
RequestPath: ctx.Path(),
UserID: ctx.Values().GetString("user_id"),
})
}
// Track error frequency
metrics.IncrementCounter("http_errors_total",
"code", string(err.ErrorCode.CanonicalName),
"endpoint", ctx.Path())
})
Performance Considerations: - Use goroutines for time-consuming operations (database writes, external API calls) - Implement circuit breakers for external service integration - Consider batching for high-volume error scenarios - Avoid depending on the Iris context in goroutines due to connection pooling - Extract all needed data from context before starting goroutines
Thread Safety: Collection functions should be thread-safe as they may be called concurrently from multiple request handlers.
Returns: *Options for method chaining
func (*Options) SetID ¶
SetID configures a static error ID that will be used for all errors handled by this Options instance. This method is useful for scenarios where you want consistent, predictable error IDs for testing, development, or specific application requirements.
Using static IDs can be helpful for: - Unit testing with predictable error responses - Development environments with consistent error identification - Specific API endpoints that need fixed error reference codes - Integration testing scenarios requiring reproducible error IDs
Parameters:
- id: The static string that will be used as the error ID for all errors
Example usage:
// Development environment with predictable IDs
if app.IsDebugMode() {
opts.SetID("debug-error-001")
}
// Testing configuration
testOpts := errors.NewOptions().SetID("test-error-id")
// API-specific error IDs
authOpts := errors.NewOptions().SetID("auth-service-error")
paymentOpts := errors.NewOptions().SetID("payment-service-error")
Warning: Using static IDs in production environments is generally not recommended as it prevents proper error correlation and tracking. Static IDs should primarily be used for development, testing, or very specific use cases where consistent error identification is required.
Implementation Note: This method internally uses SetIDGenerator with a function that always returns the provided static ID, ignoring the context parameter.
Returns: *Options for method chaining
func (*Options) SetIDGenerator ¶
func (opts *Options) SetIDGenerator(fn IDGeneratorFunc) *Options
SetIDGenerator configures a custom error ID generation function for this Options instance, replacing the default UUID-based ID generation. This enables context-aware ID generation that can correlate with request tracking, user sessions, or external monitoring systems.
Error IDs serve multiple purposes: - Unique identification for error tracking across systems - Correlation between client-side and server-side logs - Reference points for customer support and debugging - Integration with external monitoring and alerting systems
The custom generator receives the current request context, providing access to: - Request ID from the context - User identification information - Session data and metadata - Custom application-specific data
Parameters:
- fn: The custom ID generation function that receives context and returns a unique string
ID Generation Strategies:
// Request-based ID generation
opts.SetIDGenerator(func(ctx iris.Context) string {
requestID := ctx.ID()
errorSequence := atomic.AddInt64(&errorCounter, 1)
return fmt.Sprintf("%s-err-%d", requestID, errorSequence)
})
// User-session based ID generation
opts.SetIDGenerator(func(ctx iris.Context) string {
userID := ctx.Values().GetString("user_id")
sessionID := ctx.Values().GetString("session_id")
timestamp := time.Now().UnixNano()
return fmt.Sprintf("usr-%s-sess-%s-%d", userID, sessionID, timestamp)
})
// External service integration
opts.SetIDGenerator(func(ctx iris.Context) string {
return monitoringService.GenerateTraceID(ctx.ID())
})
// Hierarchical ID generation
opts.SetIDGenerator(func(ctx iris.Context) string {
serviceID := "api"
instanceID := os.Getenv("INSTANCE_ID")
requestID := ctx.ID()
return fmt.Sprintf("%s.%s.%s.%s", serviceID, instanceID, requestID, uuid.New().String()[:8])
})
Best Practices: - Ensure IDs are unique across all application instances - Include sufficient information for correlation and debugging - Keep IDs reasonably short for efficient storage and transmission - Consider using structured formats that can be easily parsed - Avoid including sensitive information in error IDs
Default Behavior: If no custom generator is set, the system generates UUIDs using the standard library's uuid package, providing guaranteed uniqueness across all instances.
Returns: *Options for method chaining
func (*Options) SetLogger ¶
func (opts *Options) SetLogger(fn LogErrorFunc) *Options
SetLogger configures a custom error logging function for this Options instance, overriding the default global LogError function. This enables route-specific or group-specific error logging behavior without affecting the global logging configuration.
The custom logger receives both the request context and the error, providing access to request-specific information for enhanced logging, monitoring, and debugging. This is particularly useful for integrating with external logging services, implementing structured logging, or creating custom error handling workflows.
Parameters:
- fn: The custom logging function to use for errors in routes configured with this Options instance
Custom Logger Capabilities: - Access to full request context (headers, user info, request ID, etc.) - Integration with external monitoring services (Sentry, DataDog, etc.) - Structured logging with custom fields and formatting - Conditional logging based on error types or request characteristics - Custom alerting and notification logic
Example usage:
// Structured logging with request context
opts.SetLogger(func(ctx iris.Context, err error) {
logger.Error("API error occurred",
"error", err.Error(),
"request_id", ctx.ID(),
"endpoint", ctx.Path(),
"method", ctx.Method(),
"user_id", ctx.Values().GetString("user_id"),
"ip_address", ctx.RemoteAddr())
})
// Integration with external monitoring
opts.SetLogger(func(ctx iris.Context, err error) {
// Log locally
ctx.Application().Logger().Error(err)
// Send to monitoring service
monitoring.RecordError(monitoring.ErrorEvent{
Error: err,
RequestID: ctx.ID(),
UserID: ctx.Values().GetString("user_id"),
Path: ctx.Path(),
Method: ctx.Method(),
})
})
// Conditional logging based on error severity
opts.SetLogger(func(ctx iris.Context, err error) {
if isHighSeverityError(err) {
alertingService.SendAlert(err, ctx)
}
defaultLogger.Log(ctx, err)
})
Performance Note: Custom loggers should avoid blocking operations or perform them in separate goroutines to prevent request processing delays.
Returns: *Options for method chaining
func (*Options) SetRenderer ¶
func (opts *Options) SetRenderer(fn ContextErrorFunc) *Options
SetRenderer configures a custom error response renderer that overrides the default JSON rendering behavior. This enables applications to customize how error responses are formatted and sent to clients, supporting various content types and presentation formats.
The renderer function receives the current request context and a fully-constructed Error instance, providing complete control over the response generation process. This includes setting custom headers, status codes, and response body formatting.
Built-in Renderers: The package provides several pre-built renderers: - Default: JSON rendering (used when no custom renderer is set) - errors.HTML: HTML error page rendering with template support - errors.Problem: RFC 7807 Problem Details for HTTP APIs format
Parameters:
- fn: The custom rendering function that generates error responses
Renderer Function Signature:
- Input: ctx (iris.Context) - The current request context
- Input: err (*Error) - The Error instance to be rendered
- Output: None (the function should write directly to the response)
Example implementations:
// Custom JSON rendering with additional metadata
opts.SetRenderer(func(ctx iris.Context, err *Error) {
response := map[string]any{
"success": false,
"error_code": err.ErrorCode.CanonicalName,
"message": err.Message,
"detail": err.Detail,
"request_id": err.ID,
"timestamp": time.Now().Unix(),
"path": ctx.Path(),
}
if err.Data != nil {
response["data"] = err.Data
}
ctx.JSON(response)
})
// XML error rendering
opts.SetRenderer(func(ctx iris.Context, err *Error) {
xmlError := struct {
XMLName xml.Name `xml:"error"`
Code string `xml:"code"`
Message string `xml:"message"`
Detail string `xml:"detail,omitempty"`
}{
Code: string(err.ErrorCode.CanonicalName),
Message: err.Message,
Detail: err.Detail,
}
ctx.XML(xmlError)
})
// Content negotiation rendering
opts.SetRenderer(func(ctx iris.Context, err *Error) {
accept := ctx.Header("Accept")
switch {
case strings.Contains(accept, "application/xml"):
renderXMLError(ctx, err)
case strings.Contains(accept, "text/html"):
errors.HTML(ctx, err)
case strings.Contains(accept, "application/problem+json"):
errors.Problem(ctx, err)
default:
ctx.JSON(err) // Default JSON
}
})
Using Built-in Renderers:
// HTML error pages with template support
opts.SetRenderer(errors.HTML)
// RFC 7807 Problem Details format
opts.SetRenderer(errors.Problem)
// Custom wrapper around built-in renderers
opts.SetRenderer(func(ctx iris.Context, err *Error) {
// Add custom headers
ctx.Header("X-Error-ID", err.ID)
ctx.Header("X-Request-ID", ctx.ID())
// Use built-in renderer
errors.Problem(ctx, err)
})
Response Responsibility: Custom renderers are responsible for: - Setting appropriate HTTP status codes (usually done automatically) - Setting content-type headers - Writing the response body - Handling any rendering errors gracefully
Thread Safety: Renderer functions should be thread-safe as they may be called concurrently from multiple request handlers.
Returns: *Options for method chaining
type Router ¶
type Router struct {
router.Router // the underline core Router, embedded to expose all of its methods.
}
Router is a wrapper around the `router.Router`. It holds the underline core Router and provides an easy way to register routes that return an error, this error is automatically handled by the framework.
All router.Router's methods that accept a context/iris.Handler are converted to accept a `Func` (func(*context.Context) error) instead.
func NewRouter ¶
NewRouter returns a new instance of the Router. It accepts a router.Router and returns a new Router. It's used to wrap the underline core router.Router with a Router that can register handlers that return an error.
Read more at the `Router` type itself.
func (*Router) Any ¶
func (r *Router) Any(path string, funcs ...Func) *router.RouteRegistry
Any registers a route for all http methods. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Any method and returns its output argument.
func (*Router) Connect ¶
Connect registers a route for the Connect http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Connect method and returns its output argument.
func (*Router) Delete ¶
Delete registers a route for the Delete http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Delete method and returns its output argument.
func (*Router) Get ¶
Get registers a route for the Get http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Get method and returns its output argument.
func (*Router) Handle ¶
func (r *Router) Handle(method, path string, funcs ...Func) *router.RouteRegistry
Handle registers a route to the server's router. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Handle method and returns its output argument.
func (*Router) HandleServer ¶
func (r *Router) HandleServer(path string, server ServerHandler)
HandleServer registers a server handler to the router. It converts the server variadic input to a compatibleServerHandler and then it calls the underline's Router.HandleServer method.
func (*Router) Head ¶
Head registers a route for the Head http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Head method and returns its output argument.
func (*Router) Options ¶
Options registers a route for the Options http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Options method and returns its output argument.
func (*Router) Patch ¶
Patch registers a route for the Patch http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Patch method and returns its output argument.
func (*Router) Post ¶
Post registers a route for the Post http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Post method and returns its output argument.
func (*Router) Put ¶
Put registers a route for the Put http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Put method and returns its output argument.
func (*Router) Query ¶
Query registers a route for the QUERY http method (RFC 10008). It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Query method and returns its output argument.
func (*Router) Subdomain ¶
Subdomain returns a new Router instance which is a subdomain of the current Router.
func (*Router) Trace ¶
Trace registers a route for the Trace http method. It converts the funcs variadic input to context.Handlers through `FuncHandlers` and then it calls the underline's Router.Trace method and returns its output argument.
func (*Router) Use ¶
Use registers a middleware to the router that runs after UseRouter but before main handlers.
func (*Router) UseRouter ¶
UseRouter registers middleware that runs before the routing itself: on every request under this router's path prefix, including unmatched routes (404) and method-not-allowed (405) requests. On a nil error the request continues to the next handler in the chain; a non-nil error is handled by HandleError and stops the request.
type Routing ¶
type Routing func(*Router)
Routing is a function type that implements the router.Controller interface for error-aware routing. It accepts an error-aware Router and defines route handlers that can return errors. These errors are automatically processed by the error handling middleware.
Routing functions provide a clean way to define error-returning routes:
app.Handle(errors.Routing(func(r *errors.Router) {
r.Get("/users/{id}", func(ctx iris.Context) error {
user, err := getUserByID(ctx.Params().Get("id"))
if err != nil {
return errors.NotFound.Wrap(err)
}
return ctx.JSON(user)
})
}))
The Routing type enables declarative error handling where any returned error is automatically converted to an appropriate HTTP response using the configured error handling options.
type ServerHandler ¶
ServerHandler is the interface that wraps the HandleRequest method.
type ValidationError ¶
type ValidationError interface {
error
// GetReason returns a human-readable description of why the validation failed.
// This message should be clear and actionable, helping users understand
// what needs to be corrected. The reason is used in error responses and
// logging to provide meaningful feedback about validation failures.
//
// Example reasons:
// - "must be a valid email address"
// - "length must be between 8 and 32 characters"
// - "must contain at least one uppercase letter"
// - "value must be greater than 0"
GetReason() string
}
ValidationError defines the interface for field validation errors that can be automatically processed by the error handling system. Custom error types that implement this interface join the validation error processing pipeline with no extra registration.
ValidationError provides a structured way to represent field-level validation failures with detailed information about what went wrong. The interface is designed to work with ErrorCodeName's Validation and Err methods for automatic error response generation.
Example implementation:
type CustomValidationError struct {
Field string
Value any
Message string
}
func (e CustomValidationError) Error() string {
return fmt.Sprintf("validation failed for field %s: %s", e.Field, e.Message)
}
func (e CustomValidationError) GetReason() string {
return e.Message
}
// Usage with error handling
validationErr := CustomValidationError{
Field: "email",
Value: "invalid-email",
Message: "must be a valid email address",
}
errors.InvalidArgument.Validation(ctx, validationErr)
return
The interface intentionally focuses on the validation reason rather than field name and value to maintain flexibility while ensuring that the essential validation information is available for error processing.
type ValidationErrors ¶
type ValidationErrors []ValidationError
ValidationErrors represents a collection of validation errors that can occur during the validation of multiple fields or complex data structures. It implements the error interface and provides a formatted representation of all validation failures.
ValidationErrors is particularly useful when validating forms, API payloads, or configuration data where multiple fields might have validation errors simultaneously. The error message format includes indexing to help identify specific validation failures.
Example usage:
var validationErrors ValidationErrors
if emailErr := validateEmail(user.Email); emailErr != nil {
validationErrors = append(validationErrors, emailErr)
}
if passwordErr := validatePassword(user.Password); passwordErr != nil {
validationErrors = append(validationErrors, passwordErr)
}
if len(validationErrors) > 0 {
errors.InvalidArgument.Validation(ctx, validationErrors...)
return
}
The resulting error message format is: "[0] first error, [1] second error" where each validation error is indexed and separated by commas.
func (ValidationErrors) Error ¶
func (errs ValidationErrors) Error() string
Error implements the error interface for ValidationErrors, providing a formatted string representation of all validation errors in the collection. Each error is prefixed with its index in square brackets and separated by commas for easy parsing and readability.
The format follows the pattern: "[index] error message, [index] error message" This indexing helps developers and users identify specific validation failures when multiple errors occur simultaneously.
Example output:
"[0] email must be a valid email address, [1] password must be at least 8 characters"
Source Files
¶
- aliases.go
- context_error_handler.go
- context_rest_renderer.go
- controller.go
- cors_error_handler.go
- error_code_map.go
- errors.go
- handler.go
- map_error_as.go
- not_found_id.go
- options.go
- pagination.go
- path_parameter_type_error_handler.go
- rate_limit_exceeded_handler.go
- recovery_handler.go
- resolver.go
- router.go
- stream.go
- validation_error.go
- version_error_handler.go
- zz_generic_methods.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package pgerrors restores the PostgreSQL-specific error mapping of the rest/errors package.
|
Package pgerrors restores the PostgreSQL-specific error mapping of the rest/errors package. |
|
Package validation provides generic field validation utilities for the Iris web framework.
|
Package validation provides generic field validation utilities for the Iris web framework. |