### Example Usage of IssueLink Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/9-types-reference.md Demonstrates how to create an IssueLink and attach it to an error using WithIssueLink. Useful for providing context to errors with external tracking. ```go issue := errors.IssueLink{ IssueURL: "https://github.com/cockroachdb/cockroach/issues/12345", Detail: "Replica unavailable", } err := errors.WithIssueLink(err, issue) ``` -------------------------------- ### Example Usage of Custom Error Formatting Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/11-advanced-topics.md Demonstrates how to use a custom error type that implements `SafeFormatter` for detailed output with `%+v`. ```go err := &MyError{cause: originalErr, severity: "high", code: 123} fmt.Printf("Error: %+v\n", err) // Output includes severity and code ``` -------------------------------- ### PII-Safe Marking Strategy Examples Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/11-advanced-topics.md Illustrates examples of data that is considered safe or unsafe to mark in error messages, based on criteria like fixed structure, non-identifiability, and origin. ```go // ✓ Safe to mark requestID := "req-12345" httpStatus := 500 tableName := "users" queryCount := 42 // ✗ Not safe to mark userEmail := "user@example.com" apiKey := "secret-xyz" sqlQuery := "SELECT * FROM users WHERE email = '" + userEmail + "'" ``` -------------------------------- ### Example Usage of GetSafeDetails Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/9-types-reference.md Demonstrates retrieving safe details from an error and iterating through the PII-free strings. Useful for safely logging or reporting error information. ```go payload := errors.GetSafeDetails(err) for _, detail := range payload.SafeDetails { fmt.Println(detail) } ``` -------------------------------- ### Stack Trace Captures Source: https://github.com/cockroachdb/errors/blob/master/README.md Utilities for capturing and retrieving stack trace information from errors. Includes functions to get a one-line source representation and the full reportable stack trace. ```go // Stack trace captures. func GetOneLineSource(err error) (file string, line int, fn string, ok bool) type ReportableStackTrace = sentry.StackTrace func GetReportableStackTrace(err error) *ReportableStackTrace ``` -------------------------------- ### Domain Management for Errors Source: https://github.com/cockroachdb/errors/blob/master/README.md Utilities for managing and checking error domains. Includes functions to get the domain of an error, create named domains, and ensure an error is not within specific domains. ```go // Domain errors. type Domain const NoDomain Domain func GetDomain(err error) Domain func NamedDomain(domainName string) Domain func PackageDomain() Domain func PackageDomainAtDepth(depth int) Domain func EnsureNotInDomain(err error, constructor DomainOverrideFn, forbiddenDomains ...Domain) error func NotInDomain(err error, doms ...Domain) bool ``` -------------------------------- ### Get the Root Cause of an Error Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use UnwrapAll() to traverse the entire error chain and retrieve the original, underlying error. ```go err := someComplexOperation() root := errors.UnwrapAll(err) // Examine the original error ``` -------------------------------- ### Add User-Facing Hints Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use WithHint() to attach suggestions or guidance for end-users directly to an error. ```go err := validateEmail(email) if err != nil { return errors.WithHint(err, "Email must be in format: user@example.com") } ``` -------------------------------- ### Create Simple Errors Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use New() for basic error messages or Newf() for formatted messages. Values known to be PII-free should be wrapped with Safe(). ```go err := errors.New("operation failed") ``` ```go userID := 123 err := errors.Newf("user %d not found", errors.Safe(userID)) ``` -------------------------------- ### Add Developer-Facing Details Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use WithDetail() to attach detailed information, such as SQL queries and parameters, useful for debugging by developers. ```go err := database.Query(sql) if err != nil { return errors.WithDetail(err, fmt.Sprintf("SQL: %s, Params: %v", sql, params)) } ``` -------------------------------- ### Get Error Type Key Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/7-encoding-formatting.md Retrieves a unique identifier for an error type, used in registration functions. Typically used when registering custom encoders or decoders. ```go func GetTypeKey(err error) TypeKey ``` -------------------------------- ### Accessing the Root Cause of an Error Chain Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/3-error-identification.md UnwrapAll retrieves the deepest cause in an error chain. If the error has no cause, it returns the error itself. This is useful for getting to the origin of a wrapped error. ```go func UnwrapAll(err error) error ``` ```go wrapped := errors.Wrap(errors.Wrap(originalErr, "level 1"), "level 2") root := errors.UnwrapAll(wrapped) // root is approximately originalErr ``` -------------------------------- ### Format and Attach User-Facing Hint to an Error Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Use WithHintf to attach a formatted hint to an error. This allows for dynamic content within user-facing suggestions. ```go err := checkConnection(host, port) if err != nil { return errors.WithHintf(err, "Could not connect to %s:%d. Check that the server is running.", host, port) } ``` -------------------------------- ### Create a Simple Error with New Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/1-error-construction.md Use `errors.New` to create an error with a simple message. It captures the stack trace at the point of call. The message is visible via `Error()` and formatting, and full details including the stack trace are available via `GetSafeDetails()`. ```go package main import ( "fmt" "github.com/cockroachdb/errors" ) func main() { err := errors.New("database connection failed") fmt.Println(err.Error()) // "database connection failed" } ``` -------------------------------- ### Retrieve All Hints from an Error Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Use GetAllHints to collect all user-facing hints associated with an error and its underlying causes. The hints are de-duplicated and returned as a slice of strings. ```go err := operation() hints := errors.GetAllHints(err) for _, hint := range hints { fmt.Println("Suggestion:", hint) } ``` -------------------------------- ### Intentional Error Hiding with Error Barriers Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/11-advanced-topics.md Use error barriers to hide original errors when they should not affect downstream code. This example shows hiding an error from an `operation` if a `fallback` operation is successful. ```go func RetryWithFallback(operation func() error, fallback func() error) error { err := operation() if err != nil { // Try fallback fallbackErr := fallback() if fallbackErr != nil { // Log original, return fallback error log.Printf("Both operation and fallback failed: %+v", err) return errors.Handled(err) // Hide operation error } return nil } return nil } ``` -------------------------------- ### Flatten All Hints into a Single String Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Use FlattenHints to retrieve all hints from an error and its causes, concatenating them into a single string. This is useful for displaying all suggestions in a compact format. ```go err := operation() hints := errors.FlattenHints(err) if hints != "" { fmt.Println("Suggestions:", hints) } ``` -------------------------------- ### WithHintf Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Formats and attaches a user-facing hint to an error. This function allows for formatted strings to be included as hints for end-users. ```APIDOC ## WithHintf ### Description Formats and attaches a user-facing hint to an error. This function allows for formatted strings to be included as hints for end-users. ### Function Signature ```go func WithHintf(err error, format string, args ...interface{}) error ``` ### Parameters #### Path Parameters - **err** (error) - Required - The error to decorate - **format** (string) - Required - Format string for the hint - **args** (...interface{}) - Optional - Format arguments ### Returns The error decorated with a formatted hint. ### Example ```go err := checkConnection(host, port) if err != nil { return errors.WithHintf(err, "Could not connect to %s:%d. Check that the server is running.", host, port) } ``` ``` -------------------------------- ### Mark Data as PII-Free for Reporting Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use Safe() when creating errors or adding details to mark data as PII-free and suitable for external reporting systems like Sentry. ```go // Include request ID (safe) err := errors.Newf("request %d failed", errors.Safe(requestID)) ``` ```go // Include query (safe) err := errors.WithSafeDetails(err, "query: %s", errors.Safe(sqlQuery)) ``` -------------------------------- ### Create a Formattable Error Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/7-encoding-formatting.md Wraps an error to provide "smart" formatting, enabling intelligent formatting even if the error's outer layer doesn't implement fmt.Formatter. ```go func Formattable(err error) fmt.Formatter ``` ```go err := operation() fmt.Printf("Error: %+v\n", errors.Formattable(err)) ``` -------------------------------- ### GetAllHints Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Retrieves all user-facing hints from an error and its underlying causes, returning them as a de-duplicated slice of strings. ```APIDOC ## GetAllHints ### Description Retrieves all user-facing hints from an error and its underlying causes, returning them as a de-duplicated slice of strings. ### Function Signature ```go func GetAllHints(err error) []string ``` ### Parameters #### Path Parameters - **err** (error) - Required - The error to extract hints from ### Returns A slice of hint strings (de-duplicated), collected via post-order traversal. ### Automatic Hints - Assertion failures receive an auto-generated hint - Issue links receive hints with their URLs - Unimplemented errors receive a standard hint ### Example ```go err := operation() hints := errors.GetAllHints(err) for _, hint := range hints { fmt.Println("Suggestion:", hint) } ``` ``` -------------------------------- ### Annotate Error with Origin Domain (Experimental) Source: https://github.com/cockroachdb/errors/blob/master/README.md Use WithDomain or HandledInDomain to mark an error with its originating package, useful at package boundaries. Experimental feature. ```go err := errors.WithDomain(err, errors.Domain("my.package.v1")) ``` ```go err := errors.HandledInDomain(err, errors.Domain("my.package.v1")) ``` ```go err := errors.HandledInDomainWithMessage(err, errors.Domain("my.package.v1"), "handled with message") ``` -------------------------------- ### Configure Internal Warning Function Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/8-reporting-stack-traces.md Sets a custom function to handle internal library warnings. Useful for integrating with existing logging systems. ```go func SetWarningFn(fn func(context.Context, string, ...interface{})) ``` ```go errors.SetWarningFn(func(ctx context.Context, format string, args ...interface{}) { log.Warningf(format, args...) }) ``` -------------------------------- ### User-Facing Details and Hints Extraction Source: https://github.com/cockroachdb/errors/blob/master/README.md Functions to retrieve user-facing details and hints associated with an error. These can be flattened into a single string for display. ```go // User-facing details and hints. func GetAllDetails(err error) []string func FlattenDetails(err error) string func GetAllHints(err error) []string func FlattenHints(err error) string ``` -------------------------------- ### Retrieve All Details from an Error Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Use GetAllDetails to collect all detail strings from an error and its causes. Details are collected via post-order traversal and are not de-duplicated. ```Go err := operation() details := errors.GetAllDetails(err) for _, detail := range details { log.Debug("Debug info:", detail) } ``` -------------------------------- ### Extract Hints and Details from Errors Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use FlattenHints() and FlattenDetails() to extract all accumulated hints and details from an error chain for display or logging. ```go err := operation() hints := errors.FlattenHints(err) if hints != "" { fmt.Println("Suggestions:", hints) } details := errors.FlattenDetails(err) if details != "" { log.Debug("Debug info:", details) } ``` -------------------------------- ### WrapWithDepthf Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/2-error-wrapping.md Like Wrapf() but with configurable stack trace capture depth. ```APIDOC ## WrapWithDepthf ### Description Wraps an error with a formatted message prefix and captures the stack trace at a specified depth. ### Method func WrapWithDepthf(depth int, err error, format string, args ...interface{}) error ### Parameters #### Path Parameters - **depth** (int) - Required - Call depth for stack trace capture - **err** (error) - Required - The error to wrap - **format** (string) - Required - Format string - **args** (...interface{}) - Optional - Format arguments ### Response Returns a wrapped error with stack trace captured at specified depth and formatted prefix. ``` -------------------------------- ### Format and Attach Debugging Detail to an Error Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Use WithDetailf for formatted debugging details. This is useful when the detail message needs to include dynamic values, similar to fmt.Sprintf. ```go err := operation() if err != nil { return errors.WithDetailf(err, "operation took %d ms, retries: %d", duration, retries) } ``` -------------------------------- ### Attach User-Facing Hint to an Error Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Use WithHint to attach a user-friendly suggestion or hint to an error. This hint is intended for end-users and is not visible in the main error message. ```go err := validateEmail(userEmail) if err != nil { return errors.WithHint(err, "Please ensure the email address is in the format user@example.com") } ``` -------------------------------- ### WrapWithDepth Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/2-error-wrapping.md Like Wrap() but allows customization of the stack trace capture depth. ```APIDOC ## WrapWithDepth ### Description Wraps an error with a message prefix and captures the stack trace at a specified depth. ### Method func WrapWithDepth(depth int, err error, msg string) error ### Parameters #### Path Parameters - **depth** (int) - Required - Call depth for stack trace capture; 0 identifies the caller - **err** (error) - Required - The error to wrap - **msg** (string) - Required - Message prefix ### Response Returns a wrapped error with stack trace captured at specified depth. ``` -------------------------------- ### New Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/1-error-construction.md Creates an error with a simple error message and captures the stack trace at the point of call. The message is suitable for Sentry reports. ```APIDOC ## New ### Description Creates an error with a simple error message and captures the stack trace at the point of call. The message is assumed to be PII-free and included in Sentry reports. ### Method func New(msg string) error ### Parameters #### Path Parameters - **msg** (string) - Required - Error message, assumed to be PII-free and included in Sentry reports ### Response An error object with captured stack trace and message. ### Request Example ```go package main import ( "fmt" "github.com/cockroachdb/errors" ) func main() { err := errors.New("database connection failed") fmt.Println(err.Error()) // "database connection failed" } ``` ``` -------------------------------- ### Traverse Error Chain Iteratively Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use UnwrapOnce() within a loop to process each error in the chain individually, printing each error before unwrapping. ```go for err != nil { fmt.Printf("Error: %v\n", err) err = errors.UnwrapOnce(err) } ``` -------------------------------- ### Formatted Error Wrapping Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use Wrapf() for more detailed context in error messages, especially when including dynamic data like item IDs. Wrap PII-free data with Safe(). ```go result, err := process(item) if err != nil { return errors.Wrapf(err, "failed to process item %d", errors.Safe(item.ID)) } ``` -------------------------------- ### Structured Telemetry for Error Keys Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/11-advanced-topics.md Defines constants for telemetry keys and demonstrates how to attach them to errors using errors.WithTelemetry. Use this to categorize and track error occurrences. ```go const ( TelemetryDatabaseTimeout = "db_timeout" TelemetryDatabaseUnavailable = "db_unavailable" TelemetryRetryExhausted = "retry_exhausted" TelemetryInvalidInput = "invalid_input" ) func ProcessRequest(req Request) error { err := validateRequest(req) if err != nil { return errors.WithTelemetry(err, TelemetryInvalidInput) } result, err := database.Execute(query) if err != nil { if isTimeout(err) { return errors.WithTelemetry(err, TelemetryDatabaseTimeout) } return errors.WithTelemetry(err, TelemetryDatabaseUnavailable) } return nil } ``` -------------------------------- ### JoinWithDepth Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/2-error-wrapping.md Similar to Join, but with configurable stack trace capture depth. ```APIDOC ## JoinWithDepth ### Description Similar to `Join()`, but with configurable stack trace capture depth. ### Function Signature ```go func JoinWithDepth(depth int, errs ...error) error ``` ### Parameters #### Path Parameters - **depth** (int) - Required - Call depth for stack trace capture - **errs** (...error) - Required - Multiple errors to join ### Returns - A single error wrapping all non-nil errors with stack trace captured at specified depth. ``` -------------------------------- ### Create Formatted UnimplementedError Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md UnimplementedErrorf creates an unimplemented error with a formatted message. It takes an IssueLink, a format string, and optional arguments for the message. ```go func UnimplementedErrorf(issueLink IssueLink, format string, args ...interface{}) error ``` -------------------------------- ### NewWithDepth Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/1-error-construction.md Similar to `New()`, this function allows customization of the stack trace capture depth, enabling more control over where the stack trace originates. ```APIDOC ## NewWithDepth ### Description Like `New()` but allows customization of the stack trace capture depth. The `depth` parameter controls how far up the call stack the trace is captured. ### Method func NewWithDepth(depth int, msg string) error ### Parameters #### Path Parameters - **depth** (int) - Required - Call depth for stack trace capture; 0 identifies the caller of NewWithDepth itself - **msg** (string) - Required - Error message, assumed to be PII-free ### Response An error object with stack trace captured at specified depth. ### Request Example ```go func wrapperFunc() error { // Capture stack trace from the caller of wrapperFunc, not from wrapperFunc itself return errors.NewWithDepth(1, "operation failed") } ``` ``` -------------------------------- ### Create a Formatted Error with Errorf (Alias for Newf) Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/1-error-construction.md Use `errors.Errorf` as an alias for `errors.Newf` to create an error with a formatted message and captured stack trace. ```go err := errors.Errorf("failed to process item: %s", item) ``` -------------------------------- ### Unwrap Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/3-error-identification.md Alias for `UnwrapOnce()` provided for compatibility with xerrors/Go 1.13 error interface. Returns the direct cause of the error. ```APIDOC ## Unwrap ### Description Alias for `UnwrapOnce()` provided for compatibility with xerrors/Go 1.13 error interface. ### Method ```go func Unwrap(err error) error ``` ### Response Returns the direct cause of the error. ``` -------------------------------- ### Create Domain Identifiers Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md Use NamedDomain, PackageDomain, or PackageDomainAtDepth to create domain identifiers for errors. PackageDomain infers the caller's package. ```go func NamedDomain(domainName string) Domain ``` ```go func PackageDomain() Domain ``` ```go func PackageDomainAtDepth(depth int) Domain ``` ```go // At package boundary, mark error as handled in this domain err := service.DoSomething() if err != nil { return errors.HandledInDomain(err, errors.PackageDomain()) } ``` -------------------------------- ### Add Safe Details for Reporting - errors.WithSafeDetails Source: https://github.com/cockroachdb/errors/blob/master/README.md Use WithSafeDetails to save strings for safe reporting. errors.Wrap/Wrapf are generally preferred over this constructor. ```go return errors.WithSafeDetails(err, "safe detail message") ``` -------------------------------- ### Creating Unimplemented Feature Errors Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md For features that are not yet implemented, return an UnimplementedError. This error can optionally link to an issue tracker for tracking implementation progress. ```go func featureX() error { return errors.UnimplementedError(errors.IssueLink{ IssueURL: "https://github.com/org/repo/issues/456", Detail: "Feature X implementation tracked here", }, "feature X is not yet supported") } ``` -------------------------------- ### Retrieve All Issue Links from Error Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md Use GetAllIssueLinks to retrieve all issue links from an error and its direct causes. This is useful for aggregating tracking information from a chain of errors. ```go err := operation() issues := errors.GetAllIssueLinks(err) for _, issue := range issues { fmt.Printf("See: %s (%s)\n", issue.IssueURL, issue.Detail) } ``` -------------------------------- ### Implement SafeDetailer for PII-free Error Details Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/9-types-reference.md Implement the SafeDetailer interface on custom error types to provide PII-free details for reporting and error inspection. ```go type SafeDetailer interface { SafeDetails() []string } ``` ```go type CustomError struct { code string // PII-free message string } func (e *CustomError) Error() string { return e.message } func (e *CustomError) SafeDetails() []string { return []string{e.code} } ``` -------------------------------- ### User-Facing Details and Hints Source: https://github.com/cockroachdb/errors/blob/master/README.md Functions for extracting user-friendly details and hints from errors. ```APIDOC ## User-facing details and hints ### Description Functions to retrieve and flatten user-readable details and hints associated with errors. ### Functions - **GetAllDetails(err error) []string**: Retrieves all user-facing details from an error. - **FlattenDetails(err error) string**: Flattens all user-facing details into a single string. - **GetAllHints(err error) []string**: Retrieves all user-facing hints from an error. - **FlattenHints(err error) string**: Flattens all user-facing hints into a single string. ``` -------------------------------- ### Newf Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/1-error-construction.md Constructs an error using a format string and arguments, similar to `fmt.Sprintf`, while also capturing the stack trace. PII-free arguments can be marked with `Safe()`. ```APIDOC ## Newf ### Description Creates an error with a formatted error message and captures the stack trace. The format string is assumed to be PII-free, and arguments can be marked as PII-free using `Safe()`. ### Method func Newf(format string, args ...interface{}) error ### Parameters #### Path Parameters - **format** (string) - Required - Format string, assumed to be PII-free - **args** (...interface{}) - Optional - Format arguments; values can be wrapped with `Safe()` to mark them as PII-free ### Response An error object with captured stack trace and formatted message. Safe details from PII-free arguments are included in Sentry reports. ### Request Example ```go err := errors.Newf("user %d not found", errors.Safe(userID)) ``` ``` -------------------------------- ### NewWithDepthf Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/1-error-construction.md Combines formatted error messages with configurable stack trace depth, allowing for detailed error reporting with controlled stack trace origins. ```APIDOC ## NewWithDepthf ### Description Like `Newf()` but with configurable stack trace capture depth. Allows creating formatted errors with a specific stack trace origin. ### Method func NewWithDepthf(depth int, format string, args ...interface{}) error ### Parameters #### Path Parameters - **depth** (int) - Required - Call depth for stack trace capture - **format** (string) - Required - Format string - **args** (...interface{}) - Optional - Format arguments ### Response An error object with stack trace captured at specified depth and formatted message. ``` -------------------------------- ### Registering Package Renames for Custom Error Types Source: https://github.com/cockroachdb/errors/blob/master/README.md Function to register package path migrations for custom error types, ensuring compatibility when package names change. ```go // Registering package renames for custom error types. func RegisterTypeMigration(previousPkgPath, previousTypeName string, newType error) ``` -------------------------------- ### WithHint Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Attaches a user-facing hint or suggestion to an error. This hint is intended for end-users and is not directly visible in the main error message. ```APIDOC ## WithHint ### Description Attaches a user-facing hint or suggestion to an error. This hint is intended for end-users and is not directly visible in the main error message. ### Function Signature ```go func WithHint(err error, msg string) error ``` ### Parameters #### Path Parameters - **err** (error) - Required - The error to decorate; if nil, returns nil - **msg** (string) - Required - Hint text for users (may contain PII) ### Returns The error decorated with a hint. ### Visibility - NOT visible in the main error message via `Error()` - Visible when formatting with `%+v` - Accessible via `GetAllHints()` and `FlattenHints()` - NOT included in Sentry reports (PII-sensitive) - De-duplicated when collected ### Use Case To provide action suggestions for end users. ### Example ```go err := validateEmail(userEmail) if err != nil { return errors.WithHint(err, "Please ensure the email address is in the format user@example.com") } ``` ``` -------------------------------- ### Check if an error matches any of multiple reference errors Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/3-error-identification.md Use `errors.IsAny` to check if an error or any of its causes matches any error in a provided list of references. This is helpful for handling multiple possible error conditions, such as timeouts or cancellations. ```go var ( errTimeout = errors.New("operation timeout") errCanceled = errors.New("operation canceled") ) err := operation() if errors.IsAny(err, errTimeout, errCanceled) { // Handle timeout or cancellation } ``` -------------------------------- ### Create a Formatted Error with Newf Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/1-error-construction.md Use `errors.Newf` to create an error with a formatted message. Arguments can be wrapped with `errors.Safe()` to mark them as PII-free. Safe details and the stack trace are included in Sentry reports. ```go err := errors.Newf("user %d not found", errors.Safe(userID)) ``` -------------------------------- ### Simplify Error Handling with errors.Wrap Source: https://github.com/cockroachdb/errors/blob/master/README.md Use errors.Wrap to simplify error handling by automatically combining WithMessage, WithStack, and WithSafeDetails. This constructor is ideal for error return paths. ```go return errors.Wrap(foo(), "foo") ``` -------------------------------- ### Implement Formatter for Custom Error Formatting Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/9-types-reference.md The Formatter interface allows for custom error formatting compatible with Go's fmt package. Consider SafeFormatter for better separation of safe/unsafe information. ```go type Formatter interface { FormatError(p Printer, verb rune) (next error) } ``` -------------------------------- ### Domain Creation Functions Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md Provides functions to create `Domain` identifiers: `NamedDomain`, `PackageDomain`, and `PackageDomainAtDepth`. ```APIDOC ## Domain Creation Functions ### Description Create domain identifiers. ### Functions #### NamedDomain - **Parameters**: `domainName` (string) - **Return**: `Domain` - **Description**: Create domain with explicit name #### PackageDomain - **Parameters**: none - **Return**: `Domain` - **Description**: Create domain from caller's package #### PackageDomainAtDepth - **Parameters**: `depth` (int) - **Return**: `Domain` - **Description**: Create domain from package at call depth ### Example ```go // At package boundary, mark error as handled in this domain err := service.DoSomething() if err != nil { return errors.HandledInDomain(err, errors.PackageDomain()) } ``` ``` -------------------------------- ### Build Sentry Report Components Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/8-reporting-stack-traces.md Builds the components of a Sentry error report, returning a Sentry Event object and additional context. Use this when you need to customize the Sentry event before capturing. ```go func BuildSentryReport(err error) (*sentry.Event, map[string]interface{}) ``` ```go event, extra := errors.BuildSentryReport(err) // Customize event as needed sentry.CaptureEvent(event) ``` -------------------------------- ### Check Against Multiple Sentinels Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use IsAny() to efficiently check if an error matches any of a list of sentinel errors, useful for retry logic. ```go if errors.IsAny(err, errTimeout, errCanceled, errDeadlineExceeded) { // Retry the operation } ``` -------------------------------- ### Marking Errors Handled in Domain Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md At package boundaries, mark an error to indicate it has been handled within the current domain. This is useful for controlling error propagation. ```go func PublicAPI(req Request) (Result, error) { result, err := internalFunc(req) if err != nil { // Mark this error as handled in this domain return Result{}, errors.HandledInDomain(err, errors.PackageDomain()) } return result, nil } ``` -------------------------------- ### Error Formatting Interfaces and Functions Source: https://github.com/cockroachdb/errors/blob/master/README.md Interfaces and functions for custom error formatting. SafeFormatter and Printer are recommended over the older Formatter interface. ```go // Error formatting. type Formatter interface { ... } // compatibility, not recommended type SafeFormatter interface { ... } type Printer interface { ... } func FormatError(err error, s fmt.State, verb rune) func Formattable(err error) fmt.Formatter ``` -------------------------------- ### Implement SafeDetailer Interface Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/8-reporting-stack-traces.md Implement this interface on custom error types to provide PII-free details for reporting. The SafeDetails method should return a slice of strings that do not contain sensitive information. ```go type SafeDetailer interface { SafeDetails() []string } ``` ```go type DatabaseError struct { query string code string // PII-free } func (e *DatabaseError) SafeDetails() []string { return []string{e.code, e.query} } ``` -------------------------------- ### Add Message Prefix - errors.WithMessage Source: https://github.com/cockroachdb/errors/blob/master/README.md Use WithMessage to add a message prefix to an error. errors.Wrap/Wrapf are generally preferred over this constructor. ```go return errors.WithMessage(err, "message prefix") ``` -------------------------------- ### BuildSentryReport Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/8-reporting-stack-traces.md Builds the components of a Sentry error report from a given error. It returns a Sentry Event object and additional context metadata. The Event is composed of error type, message, extra data, and stack trace details, with PII stripping applied to sensitive information. ```APIDOC ## BuildSentryReport ### Description Builds the components of a Sentry error report. It returns a Sentry Event object and additional context metadata. The Event is composed of error type, message, extra data, and stack trace details, with PII stripping applied to sensitive information. ### Function Signature ```go func BuildSentryReport(err error) (*sentry.Event, map[string]interface{}) ``` ### Parameters #### Path Parameters - **err** (error) - Required - The error to report ### Returns - **`*sentry.Event`**: A Sentry Event object ready for transmission - **`map[string]interface{}`**: Additional context/metadata for the report ### Example ```go event, extra := errors.BuildSentryReport(err) // Customize event as needed sentry.CaptureEvent(event) ``` ``` -------------------------------- ### Define Domain Structure Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/9-types-reference.md Represents an identifier for an error's origin package or domain. Use NamedDomain, PackageDomain, or PackageDomainAtDepth to create Domain values. ```go type Domain struct { ... } ``` -------------------------------- ### Build and Send Sentry Reports Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Use ReportError() to send an error to Sentry if telemetry is enabled, followed by a call to sentry.Flush() to ensure the report is sent. ```go err := operation() if err != nil { if telemetryEnabled { errors.ReportError(err) sentry.Flush(time.Second * 2) } return err } ``` -------------------------------- ### Embed User-Facing Hint - errors.WithHint Source: https://github.com/cockroachdb/errors/blob/master/README.md Use WithHint to embed a message string providing a suggestion for action when the error is presented to an end user. Hints are de-duplicated when flattened and are not included in Sentry reports. ```go return errors.WithHint(err, "user-facing hint") ``` -------------------------------- ### Annotate Error with Origin Domain Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md Use WithDomain to mark an error with its origin package or domain. This is an experimental API. ```go func WithDomain(err error, domain Domain) error ``` -------------------------------- ### Formattable Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/7-encoding-formatting.md Wraps an error into a fmt.Formatter for "smart" formatting, providing intelligent formatting even if the error's outer layer doesn't implement Formatter. ```APIDOC ## Formattable Wraps an error into a fmt.Formatter for "smart" formatting. ### Function Signature ```go func Formattable(err error) fmt.Formatter ``` ### Parameters #### Path Parameters - **err** (error) - Required - The error to make formattable ### Returns A fmt.Formatter that will provide intelligent formatting even if the error's outer layer doesn't implement `Formatter`. ### Example ```go err := operation() fmt.Printf("Error: %+v\n", errors.Formattable(err)) ``` ``` -------------------------------- ### Implement SafeFormatter for Separated Error Formatting Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/9-types-reference.md Implement SafeFormatter to distinguish between safe and unsafe error information during custom error formatting. It emits safe details and returns the cause. ```go type SafeFormatter interface { SafeFormatError(p Printer) (next error) } ``` ```go type MyError struct { cause error code int } func (e *MyError) Format(s fmt.State, verb rune) { errors.FormatError(e, s, verb) } func (e *MyError) SafeFormatError(p errors.Printer) (next error) { if p.Detail() { p.Printf("error code: %d", errors.Safe(e.code)) } return e.cause } ``` -------------------------------- ### Implementing Custom Error Formatting with SafeFormatter Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/11-advanced-topics.md Control how your error type is displayed using the `%+v` format specifier by implementing the `SafeFormatter` interface. This allows for custom display of error details, including severity and code. ```go type MyError struct { cause error severity string code int } func (e *MyError) Error() string { return e.cause.Error() } func (e *MyError) Unwrap() error { return e.cause } // Required for proper %+v formatting func (e *MyError) Format(s fmt.State, verb rune) { errors.FormatError(e, s, verb) } // Called during %+v formatting func (e *MyError) SafeFormatError(p errors.Printer) error { if p.Detail() { p.Printf("severity: %s", errors.Safe(e.severity)) p.Printf("code: %d", errors.Safe(e.code)) } return e.cause // Continue with cause } ``` -------------------------------- ### Check for Issue Link Annotations Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md Use HasIssueLink to check if an error or any of its causes have issue link annotations. IsIssueLink checks only the error itself. ```go func HasIssueLink(err error) bool // Check error and causes func IsIssueLink(err error) bool // Check only the error itself ``` ```go err := operation() if errors.HasIssueLink(err) { issues := errors.GetAllIssueLinks(err) // Present issues to user } ``` -------------------------------- ### Cause Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/3-error-identification.md Alias for `UnwrapAll()` provided for compatibility with github.com/pkg/errors. Returns the root cause of the error chain. ```APIDOC ## Cause ### Description Alias for `UnwrapAll()` provided for compatibility with github.com/pkg/errors. ### Method ```go func Cause(err error) error ``` ### Response Returns the root cause of the error chain. ``` -------------------------------- ### Composing a Rich Error with Multiple Annotations Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/11-advanced-topics.md Builds a complex error by sequentially wrapping it with additional information like context tags, telemetry keys, user hints, issue links, and safe details. This provides comprehensive context for debugging and user guidance. ```go func ComplexOperation(ctx context.Context, id int) error { // Start with detailed leaf error err := performOperation(id) if err != nil { err = errors.Wrapf(err, "operation failed for id %d", errors.Safe(id)) // Add context information err = errors.WithContextTags(err, ctx) // Add telemetry err = errors.WithTelemetry(err, "operation_failed", "id_" + strconv.Itoa(id)) // Add hints for users err = errors.WithHint(err, "This operation may take a few minutes. Please wait and try again.") // Link to tracking system err = errors.WithIssueLink(err, IssueLink{ IssueURL: "https://github.com/myorg/myrepo/issues/123", Detail: "Known issue with operation performance", }) // Add safe details for Sentry err = errors.WithSafeDetails(err, "attempt_count: %d", errors.Safe(attemptCount)) return err } return nil } ``` -------------------------------- ### Implement errors.SafeFormatter for Detailed Error Output Source: https://github.com/cockroachdb/errors/blob/master/README.md Optionally implement the errors.SafeFormatter interface to provide additional details for %v formatting that are not included in the standard Error() method. The FormatError() function automatically handles printing the error chain. ```go // Format() implements fmt.Formatter, is required until Go knows about FormatError. func (w *withHTTPCode) Format(s fmt.State, verb rune) { errors.FormatError(w, s, verb) } // FormatError() formats the error. func (w *withHTTPCode) SafeFormatError(p errors.Printer) (next error) { // Note: no need to print out the cause here! // FormatError() knows how to do this automatically. if p.Detail() { p.Printf("http code: %d", errors.Safe(w.code)) } return w.cause } ``` -------------------------------- ### Extract One-Line Source Information Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/8-reporting-stack-traces.md Extracts file, line number, and function name from the innermost stack trace. Returns ok=true if extraction succeeds. Useful for populating database error representations. ```go func GetOneLineSource(err error) (file string, line int, fn string, ok bool) ``` ```go err := operation() if file, line, fn, ok := errors.GetOneLineSource(err); ok { fmt.Printf("Error at %s:%d in %s\n", file, line, fn) } ``` -------------------------------- ### Implement SafeFormatter Interface for Custom Errors Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/7-encoding-formatting.md Implement this interface on custom error types to control how details are displayed in `%+v` output, separating safe and unsafe formatting. ```go type SafeFormatter interface { SafeFormatError(p Printer) (next error) } ``` ```go func (e *MyError) SafeFormatError(p errors.Printer) (next error) { if p.Detail() { p.Printf("code: %d", errors.Safe(e.code)) } return e.cause } ``` -------------------------------- ### Opt-in PII-Safe String to Sentry Reports Source: https://github.com/cockroachdb/errors/blob/master/README.md Use errors.WithSafeDetails to attach additional arbitrary strings to an error that will be included in Sentry reports but not the main error message. ```go err = errors.WithSafeDetails(err, "additional data: %s", errors.Safe("hello")) ``` -------------------------------- ### Register Multiple Type Migrations Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/11-advanced-topics.md Handle cases where an error type has been renamed multiple times by registering multiple type migrations. Each migration maps a specific previous version to the current type. ```go func init() { // Old path v1 -> current errors.RegisterTypeMigration("github.com/old/v1", "*old.ErrorType", ¤t.Error{}) // Old path v2 -> current errors.RegisterTypeMigration("github.com/old/v2", "*oldv2.ErrorType", ¤t.Error{}) } ``` -------------------------------- ### As Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/3-error-identification.md Searches an error chain for the first error that can be assigned to a target type. If found, the target is updated with the matching error value. ```APIDOC ## As ### Description Finds the first error in an error chain matching a target type. ### Method `func As(err error, target interface{}) bool` ### Parameters #### Path Parameters - **err** (error) - Required - The error to search - **target** (interface{}) - Required - Pointer to a type or interface to match; must be a non-nil pointer ### Returns `true` if a matching error was found and assigned to target. ### Behavior - Searches the error chain for an error assignable to target's type - If found, sets target to that error value and returns true - Supports custom `As(interface{}) bool` method on errors - Also recurses through causes with `Cause()` method (unlike standard library) - Panics if target is not a non-nil pointer to a type implementing error or an interface type ### Example ```go var customErr *CustomErrorType err := someOperation() if errors.As(err, &customErr) { // Use customErr.ErrorCode, etc. } ``` ``` -------------------------------- ### Wrapf Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/2-error-wrapping.md Wraps an error with a formatted message prefix and captures the stack trace. ```APIDOC ## Wrapf ### Description Wraps an error with a formatted message prefix and captures the stack trace. ### Method func Wrapf(err error, format string, args ...interface{}) error ### Parameters #### Path Parameters - **err** (error) - Required - The error to wrap - **format** (string) - Required - Format string for the prefix, assumed to be PII-free - **args** (...interface{}) - Optional - Format arguments; values can be wrapped with `Safe()` ### Response Returns a wrapped error with formatted prefix. ### Request Example ```go result, err := processRequest(req) if err != nil { return errors.Wrapf(err, "request %d processing failed", errors.Safe(req.ID)) } ``` ``` -------------------------------- ### GetAllIssueLinks Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md Retrieves all issue links from an error and its direct causes. ```APIDOC ## GetAllIssueLinks ### Description Retrieves all issue links from an error and its direct causes. ### Method ```go func GetAllIssueLinks(err error) []IssueLink ``` ### Parameters #### Path Parameters - **err** (error) - Required - The error to search ### Returns A slice of `IssueLink` values from the error and its direct causes. ### Example ```go er := operation() issues := errors.GetAllIssueLinks(er) for _, issue := range issues { fmt.Printf("See: %s (%s)\n", issue.IssueURL, issue.Detail) } ``` ``` -------------------------------- ### Wrap Errors with Context Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/10-usage-patterns.md Wrap errors at function boundaries using Wrap() to add context and automatically capture a stack trace. Include relevant context in the wrap message. ```go func readConfig(path string) (config, error) { data, err := ioutil.ReadFile(path) if err != nil { return config{}, errors.Wrap(err, "failed to read config") } return parseConfig(data) } ``` -------------------------------- ### Join Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/2-error-wrapping.md Combines multiple errors into a single error that wraps them all. Nil errors are discarded. ```APIDOC ## Join ### Description Combines multiple errors into a single error that wraps them all. Nil errors are discarded. ### Function Signature ```go func Join(errs ...error) error ``` ### Parameters #### Path Parameters - **errs** (...error) - Required - Multiple errors to join; nil values are discarded ### Returns - A single error that wraps all non-nil errors, formatted with newlines between messages. Returns nil if all errors are nil. ### Example ```go err1 := database.Close() err2 := cache.Flush() if err := errors.Join(err1, err2); err != nil { return err } ``` ``` -------------------------------- ### Create UnimplementedError Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md Use UnimplementedError to create a leaf error indicating that a feature is not yet implemented. It requires an IssueLink for tracking and a message describing the unimplemented feature. ```go func featureX() error { return errors.UnimplementedError(IssueLink{ IssueURL: "https://github.com/cockroachdb/cockroach/issues/45678", Detail: "Feature X implementation", }, "feature X is not yet supported") } ``` -------------------------------- ### Formatter Interface Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/9-types-reference.md An interface for custom error formatting compatible with Go's fmt package. It allows for custom error string representation. ```APIDOC ## Formatter Interface ### Description An interface for custom error formatting (used with Go's fmt package). ### Methods - `FormatError(p Printer, verb rune) error`: Formats the error and returns the cause to continue formatting. ### Note Consider implementing `SafeFormatter` instead for better separation of safe/unsafe information. ### Compatibility This matches the error formatting interface proposed for Go 2. ``` -------------------------------- ### Opt-in PII-Safe Value to Error Message Source: https://github.com/cockroachdb/errors/blob/master/README.md Use errors.Safe() to wrap values passed to ...f() constructors, ensuring they are included in Sentry reports and the main error message. ```go err := errors.Newf("my code: %d", errors.Safe(123)) ``` -------------------------------- ### WithStackDepth Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/2-error-wrapping.md Similar to WithStack, but allows customization of the stack trace capture depth. ```APIDOC ## WithStackDepth ### Description Similar to `WithStack()`, but allows customization of the stack trace capture depth. ### Function Signature ```go func WithStackDepth(err error, depth int) error ``` ### Parameters #### Path Parameters - **err** (error) - Required - The error to annotate - **depth** (int) - Required - Call depth; 0 identifies the caller of WithStackDepth itself ### Returns - The error annotated with stack trace captured at specified depth. ``` -------------------------------- ### Add a formatted message prefix without capturing stack trace Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/2-error-wrapping.md Use WithMessagef to add a formatted message prefix to an error without capturing a stack trace. Format arguments are separated into safe/unsafe for Sentry reporting. ```go func WithMessagef(err error, format string, args ...interface{}) error ``` -------------------------------- ### Registering Package Renames Source: https://github.com/cockroachdb/errors/blob/master/README.md Function to register package path migrations for custom error types. ```APIDOC ## Registering Package Renames ### Description Allows registration of migrations for custom error types when their package paths change. ### Function - **RegisterTypeMigration(previousPkgPath, previousTypeName string, newType error)** ``` -------------------------------- ### Mark a Value as PII-Free for Reporting Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/5-error-details-hints.md Use Safe to wrap a value, indicating it is PII-free and suitable for inclusion in reports and safe details. This is commonly used with error formatting functions. ```Go userID := 12345 err := errors.Newf("user %d not found", errors.Safe(userID)) // userID is included in Sentry reports ``` -------------------------------- ### Encode and Decode Error for Network Transmission Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/9-types-reference.md Shows how to serialize an error into a protobuf representation for network transmission using EncodeError and deserialize it back using DecodeError. Preserves the error chain and metadata. ```go ctx := context.Background() encoded := errors.EncodeError(ctx, err) data, _ := proto.Marshal(&encoded) // transmit data... proto.Unmarshal(receivedData, &encoded) decodedErr := errors.DecodeError(ctx, encoded) ``` -------------------------------- ### UnimplementedError Source: https://github.com/cockroachdb/errors/blob/master/_autodocs/6-error-metadata.md Creates a leaf error indicating that a feature is not yet implemented, including a link to a tracking issue. ```APIDOC ## UnimplementedError ### Description Creates a leaf error indicating that a feature is not yet implemented. ### Method ```go func UnimplementedError(issueLink IssueLink, msg string) error ``` ### Parameters #### Path Parameters - **issueLink** (IssueLink) - Required - Link to tracking issue for the unimplemented feature - **msg** (string) - Required - Message describing what is not implemented ### Returns An error marked as unimplemented with issue tracking. ### Example ```go func featureX() error { return errors.UnimplementedError(IssueLink{ IssueURL: "https://github.com/cockroachdb/cockroach/issues/45678", Detail: "Feature X implementation", }, "feature X is not yet supported") } ``` ```