Documentation
¶
Overview ¶
Package errific provides enhanced error handling for Go with caller information, clean error wrapping, and helpful formatting methods.
errific simplifies error creation by adding runtime caller metadata (file, line, function) to errors, making debugging easier without sacrificing clean error messages. It supports error chaining, formatted messages, and configurable output options including stack traces.
Basic usage:
var ErrProcessThing errific.Err = "error processing thing"
func process() error {
if err := validate(); err != nil {
return ErrProcessThing.New(err)
}
return nil
}
The resulting error includes caller information:
error processing thing [mypackage/file.go:42.process] validation failed [mypackage/validate.go:15.validate]
Configuration options include caller position (prefix/suffix/disabled), layout (newline/inline), stack traces, and path trimming.
Index ¶
- Constants
- Variables
- func Configure(opts ...Option)
- func GetCode(err error) string
- func GetCorrelationID(err error) string
- func GetDocs(err error) string
- func GetDuration(err error) time.Duration
- func GetHTTPStatus(err error) int
- func GetHelp(err error) string
- func GetLabel(err error, key string) string
- func GetLabels(err error) map[string]string
- func GetMCPCode(err error) int
- func GetMaxRetries(err error) int
- func GetRequestID(err error) string
- func GetRetryAfter(err error) time.Duration
- func GetSessionID(err error) string
- func GetSuggestion(err error) string
- func GetTags(err error) []string
- func GetTimestamp(err error) time.Time
- func GetUserID(err error) string
- func IsRetryable(err error) bool
- type Category
- type Context
- type Err
- func (e Err) Error() string
- func (e Err) Errorf(a ...any) errific
- func (e Err) New(errs ...error) errific
- func (e Err) WithCategory(category Category) errific
- func (e Err) WithCode(code string) errific
- func (e Err) WithContext(ctx Context) errific
- func (e Err) WithCorrelationID(id string) errific
- func (e Err) WithDocs(url string) errific
- func (e Err) WithDuration(d time.Duration) errific
- func (e Err) WithHTTPStatus(status int) errific
- func (e Err) WithHelp(text string) errific
- func (e Err) WithLabel(key, value string) errific
- func (e Err) WithLabels(labels map[string]string) errific
- func (e Err) WithMCPCode(code int) errific
- func (e Err) WithMaxRetries(max int) errific
- func (e Err) WithRequestID(id string) errific
- func (e Err) WithRetryAfter(duration time.Duration) errific
- func (e Err) WithRetryable(retryable bool) errific
- func (e Err) WithSessionID(id string) errific
- func (e Err) WithSuggestion(text string) errific
- func (e Err) WithTags(tags ...string) errific
- func (e Err) WithTimestamp(t time.Time) errific
- func (e Err) WithUserID(id string) errific
- func (e Err) Withf(format string, a ...any) errific
- func (e Err) Wrapf(format string, a ...any) errific
- type MCPError
- type Option
Constants ¶
const ( // Suffix adds caller information at the end of the error message. // This is default. Suffix callerOption = iota // Prefix adds caller information at the beginning of the error message. Prefix // Disabled does not include caller information in the error message. Disabled )
const ( // Newline joins errors with \n. // This is default. Newline layoutOption = iota // Inline wraps errors with ↩. Inline )
const ( // OutputPretty formats errors as human-readable multi-line text with all metadata. // // Example: // user not found [main.go:20.GetUser] // code: USER_404 // context: {user_id: user-123, source: database} // http_status: 400 OutputPretty outputFormatOption = iota // OutputJSON formats errors as compact JSON. // This is the default. // Useful for structured logging and machine processing. // // Example: // {"error":"user not found","caller":"main.go:20","code":"USER_404",...} OutputJSON // OutputJSONPretty formats errors as indented JSON. // Useful for documentation, debugging, and human-readable JSON output. // // Example: // { // "error": "user not found", // "code": "USER_404", // "caller": "main.go:20" // } OutputJSONPretty // OutputCompact formats errors as single-line text with key=value pairs. // Useful for log aggregation systems. // // Example: // user not found [main.go:20] code=USER_404 user_id=user-123 http_status=400 OutputCompact )
const ( // VerbosityMinimal shows only the error message and caller. // // Example: // user not found [main.go:20.GetUser] VerbosityMinimal verbosityOption = iota // VerbosityStandard shows message, caller, code, category, and context. // Good balance for most applications. // // Example: // user not found [main.go:20.GetUser] // code: USER_404 // category: validation // context: {user_id: user-123} VerbosityStandard // VerbosityFull shows all non-empty fields (default). // Recommended for debugging and development. // // Example: // user not found [main.go:20.GetUser] // code: USER_404 // category: validation // context: {user_id: user-123, source: database} // http_status: 400 // retryable: true // correlation_id: trace-123 // help: Check if user exists VerbosityFull // VerbosityCustom allows fine-grained control via individual field flags. // Use with Show* and Hide* options. VerbosityCustom )
const ( // MCPParseError represents invalid JSON was received by the server. MCPParseError = -32700 // MCPInvalidRequest represents the JSON sent is not a valid Request object. MCPInvalidRequest = -32600 // MCPMethodNotFound represents the method does not exist / is not available. MCPMethodNotFound = -32601 // MCPInvalidParams represents invalid method parameter(s). MCPInvalidParams = -32602 // MCPInternalError represents internal JSON-RPC error. MCPInternalError = -32603 // MCPToolError represents a tool execution error (custom range -32000 to -32099). MCPToolError = -32000 )
MCP error codes following JSON-RPC 2.0 specification. These codes enable errific errors to be serialized in MCP-compatible format for AI tool calling and Model Context Protocol integration.
Valid code ranges per JSON-RPC 2.0 specification:
- Standard errors: -32768 to -32000 (reserved by JSON-RPC 2.0)
- Server errors: -32000 to -32099 (available for application-specific errors)
When using WithMCPCode(), use the predefined constants below or custom codes in the -32000 to -32099 range for application-specific errors.
References:
- JSON-RPC 2.0: https://www.jsonrpc.org/specification
- Model Context Protocol: https://modelcontextprotocol.io
const ( // Trim current working directory from filenames. TrimCWD trimCWDOption = true )
const ( // Include stacktrace in error message. WithStack withStackTraceOption = true )
Variables ¶
var ( // ShowCode includes error code in output. ShowCode = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideCode excludes error code from output. HideCode = fieldVisibilityOption{/* contains filtered or unexported fields */} // ShowCategory includes error category in output. ShowCategory = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideCategory excludes error category from output. HideCategory = fieldVisibilityOption{/* contains filtered or unexported fields */} // ShowContext includes structured context in output. ShowContext = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideContext excludes structured context from output. HideContext = fieldVisibilityOption{/* contains filtered or unexported fields */} // ShowHTTPStatus includes HTTP status code in output. ShowHTTPStatus = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideHTTPStatus excludes HTTP status code from output. HideHTTPStatus = fieldVisibilityOption{/* contains filtered or unexported fields */} // ShowRetryMetadata includes retry information (retryable, retry_after, max_retries) in output. ShowRetryMetadata = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideRetryMetadata excludes retry information from output. HideRetryMetadata = fieldVisibilityOption{/* contains filtered or unexported fields */} // ShowMCPData includes MCP-related fields (correlation_id, help, suggestion, etc.) in output. ShowMCPData = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideMCPData excludes MCP-related fields from output. HideMCPData = fieldVisibilityOption{/* contains filtered or unexported fields */} // ShowTags includes semantic tags in output. ShowTags = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideTags excludes semantic tags from output. HideTags = fieldVisibilityOption{/* contains filtered or unexported fields */} // ShowLabels includes key-value labels in output. ShowLabels = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideLabels excludes key-value labels from output. HideLabels = fieldVisibilityOption{/* contains filtered or unexported fields */} // ShowTimestamps includes timestamp and duration in output. ShowTimestamps = fieldVisibilityOption{/* contains filtered or unexported fields */} // HideTimestamps excludes timestamp and duration from output. HideTimestamps = fieldVisibilityOption{/* contains filtered or unexported fields */} )
var ( // TrimPrefixes from caller frame filenames. TrimPrefixes = func(prefixes ...string) trimPrefixesOption { return trimPrefixesOption{prefixes: prefixes} } )
Functions ¶
func GetCode ¶
GetCode extracts the error code from an error. Returns an empty string if the error doesn't have a code.
func GetCorrelationID ¶
GetCorrelationID extracts the correlation ID from an error. Returns an empty string if no correlation ID is set.
func GetDocs ¶
GetDocs extracts the documentation URL from an error. Returns an empty string if no docs URL is set.
func GetDuration ¶
GetDuration extracts the operation duration from an error. Returns 0 if no duration is set.
func GetHTTPStatus ¶
GetHTTPStatus extracts the HTTP status code from an error. Returns 0 if no HTTP status is set.
func GetHelp ¶
GetHelp extracts the help text from an error. Returns an empty string if no help text is set.
func GetLabel ¶
GetLabel extracts a specific label value from an error. Returns an empty string if the label doesn't exist.
func GetMCPCode ¶
GetMCPCode extracts the MCP error code from an error. Returns 0 if the error is nil or doesn't have an MCP code.
func GetMaxRetries ¶
GetMaxRetries extracts the maximum retry count from an error. Returns 0 if no max retries is set.
func GetRequestID ¶
GetRequestID extracts the request ID from an error. Returns an empty string if no request ID is set.
func GetRetryAfter ¶
GetRetryAfter extracts the suggested retry delay from an error. Returns 0 if no retry delay is set.
func GetSessionID ¶
GetSessionID extracts the session ID from an error. Returns an empty string if no session ID is set.
func GetSuggestion ¶
GetSuggestion extracts the suggestion text from an error. Returns an empty string if no suggestion is set.
func GetTimestamp ¶
GetTimestamp extracts the timestamp from an error. Returns zero time if no timestamp is set.
func GetUserID ¶
GetUserID extracts the user ID from an error. Returns an empty string if no user ID is set.
func IsRetryable ¶
IsRetryable checks if an error is marked as retryable. Returns false if the error is not retryable or not an errific error.
Types ¶
type Category ¶
type Category string
Category represents the category of an error for automated handling.
const ( // CategoryClient represents client-side errors (4xx). CategoryClient Category = "client" // CategoryServer represents server-side errors (5xx). CategoryServer Category = "server" // CategoryNetwork represents network connectivity errors. CategoryNetwork Category = "network" // CategoryValidation represents input validation errors. CategoryValidation Category = "validation" // CategoryNotFound represents resource not found errors (404). CategoryNotFound Category = "not_found" CategoryUnauthorized Category = "unauthorized" // CategoryTimeout represents timeout errors. CategoryTimeout Category = "timeout" )
func GetCategory ¶
GetCategory extracts the error category from an error. Returns an empty category if the error doesn't have one.
type Context ¶
Context is a map of key-value pairs that provides additional context for errors. This structured data can be used for debugging, logging, and automated error handling.
func GetContext ¶
GetContext extracts structured context from an error. Returns nil if the error doesn't have context data. This function works with any error type but only extracts context from errific errors.
type Err ¶
type Err string
Err string type.
To include runtime caller information on the error, one of the Err methods, other than Error(), must be called.
For examples see the example tests. All examples demonstrate using exported errors as a recommended best practice because exported errors enable unit-tests that assert expected errors such as: assert.ErrorIs(t, err, ErrProcessThing).
func (Err) Errorf ¶
Errorf returns an error using Err formatted as text. Use Errorf if your Err string itself contains fmt format specifiers.
var ErrProcessThing errific.Err = "error processing thing id: '%s'"
return ErrProcessThing.Errorf("abc")
func (Err) New ¶
New returns an error using Err as text with errors joined.
var ErrProcessThing errific.Err = "error processing a thing" return ErrProcessThing.New(err)
func (Err) WithCategory ¶
func (Err) WithContext ¶
func (Err) WithCorrelationID ¶
func (Err) WithDuration ¶
func (Err) WithHTTPStatus ¶
func (Err) WithLabels ¶
func (Err) WithMCPCode ¶
func (Err) WithMaxRetries ¶
func (Err) WithRequestID ¶
func (Err) WithRetryAfter ¶
func (Err) WithRetryable ¶
func (Err) WithSessionID ¶
func (Err) WithSuggestion ¶
func (Err) WithTimestamp ¶
func (Err) WithUserID ¶
type MCPError ¶
type MCPError struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
}
MCPError represents a Model Context Protocol error in JSON-RPC 2.0 format. This format is compatible with MCP server error responses and AI tool calling protocols.
func ToMCPError ¶
ToMCPError converts any error to MCP JSON-RPC 2.0 format. If the error is an errific error with an MCP code set, it uses that code. Otherwise, it defaults to MCPInternalError. Returns a zero MCPError if err is nil.
mcpErr := ToMCPError(err) json.NewEncoder(w).Encode(mcpErr)

