errorhandling

package
v1.10.1 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 7 Imported by: 0

README

Error Handling

Centralized error reporting and formatting for consistent CLI behavior.

Key Features:

  • Structured error logging
  • Clean stack trace formatting (in debug mode)
  • Contextual help integration
  • Consistent exit code management

For detailed documentation and best practices, see the Error Handling Component Documentation.

Documentation

Overview

Package errorhandling provides structured, user-friendly error reporting for CLI tools built with GTB.

The ErrorHandler interface offers Check (route through the reporting pipeline), Fatal (report and exit), Error (non-terminating report), and Warn methods. Errors are rendered with optional user-facing hints (via cockroachdb/errors WithHint/WithHintf) and help channel references (Slack, Teams) configured through HelpConfig.

Stack traces from cockroachdb/errors are automatically extracted and displayed in debug mode, providing rich diagnostic context without cluttering normal output.

Index

Examples

Constants

View Source
const (
	LevelFatal    = "fatal"
	LevelError    = "error"
	LevelWarn     = "warn"
	KeyStacktrace = "stacktrace"
	KeyHelp       = "help"
	KeyHints      = "hints"
	KeyDetails    = "details"
)

Variables

View Source
var (
	ErrNotImplemented = errors.New("command not yet implemented")
	ErrRunSubCommand  = errors.New("subcommand required")
)

Functions

func NewAssertionFailure

func NewAssertionFailure(format string, args ...any) error

NewAssertionFailure creates an error denoting a programming bug.

func NewErrNotImplemented

func NewErrNotImplemented(issueURL string) error

NewErrNotImplemented creates an unimplemented error with an optional issue tracker link.

func WithUserHint

func WithUserHint(err error, hint string) error

WithUserHint attaches a user-facing recovery suggestion to an error.

Example
package main

import (
	"fmt"

	"github.com/cockroachdb/errors"

	"github.com/phpboyscout/go-tool-base/pkg/errorhandling"
)

func main() {
	err := errors.New("connection refused")
	hinted := errorhandling.WithUserHint(err, "Check that the server is running and the port is correct")

	fmt.Println(errors.FlattenHints(hinted))
}
Output:
Check that the server is running and the port is correct

func WithUserHintf

func WithUserHintf(err error, format string, args ...any) error

WithUserHintf attaches a formatted user-facing recovery suggestion.

func WrapWithHint

func WrapWithHint(err error, msg string, hint string) error

WrapWithHint wraps an error with a message and attaches a user-facing hint.

Example
package main

import (
	"fmt"

	"github.com/cockroachdb/errors"

	"github.com/phpboyscout/go-tool-base/pkg/errorhandling"
)

func main() {
	err := errors.New("file not found")
	wrapped := errorhandling.WrapWithHint(err, "loading config", "Run 'mytool init' to create the config file")

	fmt.Println(wrapped.Error())
	fmt.Println(errors.FlattenHints(wrapped))
}
Output:
loading config: file not found
Run 'mytool init' to create the config file

Types

type ErrorHandler

type ErrorHandler interface {
	Check(err error, prefix string, level string, cmd ...*cobra.Command)
	Fatal(err error, prefixes ...string)
	Error(err error, prefixes ...string)
	Warn(err error, prefixes ...string)
	SetUsage(usage func() error)
}

ErrorHandler defines the interface for structured error reporting. It formats errors with hints, stack traces, and help channel information, then routes them to the appropriate output (logger, writer, or exit).

func New

func New(l logger.Logger, help HelpConfig, opts ...Option) ErrorHandler

New creates an ErrorHandler with the given logger and help config. Options can override the exit function, output writer, or other defaults.

Example
package main

import (
	"github.com/phpboyscout/go-tool-base/pkg/errorhandling"
)

func main() {
	handler := errorhandling.New(nil, nil)
	_ = handler // Use handler.Check, handler.Error, handler.Fatal, handler.Warn
}

type ExitFunc

type ExitFunc func(code int)

ExitFunc is the function called to terminate the process. Defaults to os.Exit. Override via WithExitFunc for testing.

type HelpConfig

type HelpConfig interface {
	SupportMessage() string
}

HelpConfig is the interface for providing contextual support information when errors occur. Implementations return a human-readable message directing users to a support channel. Returning an empty string suppresses the help output.

type Option

type Option func(*StandardErrorHandler)

Option is a functional option for configuring a StandardErrorHandler.

func WithExitFunc

func WithExitFunc(exit ExitFunc) Option

WithExitFunc allows injection of a custom exit handler (e.g. for testing).

func WithWriter

func WithWriter(w io.Writer) Option

WithWriter allows injection of a custom output writer.

type SlackHelp

type SlackHelp struct {
	Team    string `json:"team" yaml:"team"`
	Channel string `json:"channel" yaml:"channel"`
}

SlackHelp provides Slack channel contact details as a support message.

Example
package main

import (
	"fmt"

	"github.com/phpboyscout/go-tool-base/pkg/errorhandling"
)

func main() {
	help := errorhandling.SlackHelp{
		Team:    "mycompany",
		Channel: "#dev-support",
	}

	fmt.Println(help.SupportMessage())
}
Output:
For assistance, contact mycompany via Slack channel #dev-support

func (SlackHelp) SupportMessage

func (s SlackHelp) SupportMessage() string

type StandardErrorHandler

type StandardErrorHandler struct {
	Logger logger.Logger
	Help   HelpConfig
	Exit   ExitFunc
	Writer io.Writer
	Usage  func() error
}

StandardErrorHandler is the default ErrorHandler implementation. It extracts hints, details, and stack traces from cockroachdb/errors and formats them for terminal or structured output.

func (*StandardErrorHandler) Check

func (h *StandardErrorHandler) Check(err error, prefix string, level string, cmd ...*cobra.Command)

func (*StandardErrorHandler) Error

func (h *StandardErrorHandler) Error(err error, prefixes ...string)

func (*StandardErrorHandler) Fatal

func (h *StandardErrorHandler) Fatal(err error, prefixes ...string)

func (*StandardErrorHandler) SetUsage

func (h *StandardErrorHandler) SetUsage(usage func() error)

func (*StandardErrorHandler) Warn

func (h *StandardErrorHandler) Warn(err error, prefixes ...string)

type TeamsHelp

type TeamsHelp struct {
	Team    string `json:"team" yaml:"team"`
	Channel string `json:"channel" yaml:"channel"`
}

TeamsHelp provides Microsoft Teams channel contact details as a support message.

func (TeamsHelp) SupportMessage

func (t TeamsHelp) SupportMessage() string

Jump to

Keyboard shortcuts

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