errors

package
v1.33.18 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package errors provides enhanced error handling with codes, stack traces, and context.

Index

Examples

Constants

View Source
const (
	ExitSuccess    = 0
	ExitError      = 1
	ExitUsage      = 2
	ExitConfig     = 10
	ExitValidation = 11
	ExitIO         = 20
	ExitNotFound   = 21
	ExitBuild      = 30
	ExitPlugin     = 31
	ExitDependency = 40
)

Exit codes for the buffalo CLI. These follow a stable numbering scheme so that scripts and CI pipelines can react to specific failure classes:

0   success
1   generic / unclassified error
2   misuse of CLI (bad flags, unknown command) — owned by cobra
10  configuration error (missing/invalid buffalo.yaml, bad schema)
11  validation error (config or input failed semantic checks)
20  IO error (read/write/permission)
21  not found (file, target, plugin)
30  build / compilation failure
31  plugin failure
40  dependency / network error

Variables

This section is empty.

Functions

func As

func As(err error, target interface{}) bool

As finds the first error in err's chain that matches target.

func ExitCode added in v1.33.16

func ExitCode(err error) int

ExitCode maps an *Error to a stable shell exit code. Returns ExitError for anything not matched by a specific category.

func Is

func Is(err, target error) bool

Is checks if err matches target using errors.Is.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	err1 := errors.New(errors.ErrNotFound, "file not found")
	err2 := errors.New(errors.ErrNotFound, "different message")

	if errors.Is(err1, err2) {
		fmt.Println("Both errors have the same error code")
	}
}
Output:
Both errors have the same error code

func Unwrap

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	originalErr := fmt.Errorf("disk full")
	wrappedErr := errors.Wrap(originalErr, errors.ErrIO, "failed to write file")

	unwrapped := errors.Unwrap(wrappedErr)
	fmt.Println(unwrapped)
}
Output:
disk full

Types

type Error

type Error struct {
	// Code is the error code for categorization.
	Code ErrorCode
	// Message is the error message.
	Message string
	// Cause is the underlying error that caused this error.
	Cause error
	// Stack is the call stack where the error was created.
	Stack []uintptr
	// Context contains additional contextual information.
	Context map[string]interface{}
}

Error represents an enhanced error with additional context.

Example (PracticalUsage)

Example of error handling in practice

package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	// Simulating a function that might fail
	err := readProtoFile("/path/to/file.proto")
	if err != nil {
		// Check for specific error code
		if buffErr, ok := err.(*errors.Error); ok {
			switch buffErr.Code {
			case errors.ErrNotFound:
				fmt.Println("Proto file not found - please check the path")
			case errors.ErrIO:
				fmt.Println("Failed to read proto file - check permissions")
			default:
				fmt.Println("Unexpected error occurred")
			}
		}
	}
}

func readProtoFile(path string) error {

	return errors.New(errors.ErrNotFound, "proto file %s not found", path)
}
Output:
Proto file not found - please check the path

func New

func New(code ErrorCode, message string, args ...interface{}) *Error

New creates a new Error with the given code and message.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	err := errors.New(errors.ErrNotFound, "proto file not found")
	fmt.Println(err)
}
Output:
[NOT_FOUND] proto file not found
Example (WithFormatting)
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	err := errors.New(errors.ErrNotFound, "file %s not found in directory %s", "test.proto", "/protos")
	fmt.Println(err)
}
Output:
[NOT_FOUND] file test.proto not found in directory /protos

func Wrap

func Wrap(err error, code ErrorCode, message string, args ...interface{}) *Error

Wrap wraps an existing error with additional context.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	originalErr := fmt.Errorf("connection refused")
	err := errors.Wrap(originalErr, errors.ErrIO, "failed to connect to server")
	fmt.Println(err)
}
Output:
[IO_ERROR] failed to connect to server: connection refused

func (*Error) DetailedError

func (e *Error) DetailedError() string

DetailedError returns a detailed error message with stack trace and context.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	err := errors.New(errors.ErrConfig, "invalid configuration").
		WithContext("config_file", "/etc/buffalo/config.yaml").
		WithContext("field", "compilers.python.path")

	// DetailedError provides comprehensive information
	// including message, code, context, and stack trace
	detailed := err.DetailedError()
	fmt.Printf("Detailed error length: %d bytes\n", len(detailed))
	// Output will include all error details
}

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) GetContext

func (e *Error) GetContext(key string) (interface{}, bool)

GetContext retrieves a context value.

func (*Error) Is

func (e *Error) Is(target error) bool

Is checks if the error matches the target error.

func (*Error) StackTrace

func (e *Error) StackTrace() string

StackTrace returns the formatted stack trace.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	err := errors.New(errors.ErrInternal, "internal error")
	stack := err.StackTrace()

	// Stack trace will contain function names and line numbers
	fmt.Printf("Stack trace captured: %d bytes\n", len(stack))
	// Output example will vary, but demonstrates stack capture
}

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the cause of the error for errors.Unwrap.

func (*Error) WithContext

func (e *Error) WithContext(key string, value interface{}) *Error

WithContext adds context to the error.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	err := errors.New(errors.ErrCompilation, "protoc compilation failed").
		WithContext("file", "user.proto").
		WithContext("line", 42).
		WithContext("column", 10)

	if file, ok := err.GetContext("file"); ok {
		fmt.Printf("Error in file: %v\n", file)
	}
	if line, ok := err.GetContext("line"); ok {
		fmt.Printf("At line: %v\n", line)
	}
}
Output:
Error in file: user.proto
At line: 42

func (*Error) WithContextMap

func (e *Error) WithContextMap(context map[string]interface{}) *Error

WithContextMap adds multiple context values.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/errors"
)

func main() {
	context := map[string]interface{}{
		"proto_file": "service.proto",
		"language":   "python",
		"output_dir": "/gen/python",
	}

	err := errors.New(errors.ErrCompilation, "compilation failed").
		WithContextMap(context)

	if protoFile, ok := err.GetContext("proto_file"); ok {
		fmt.Printf("Proto file: %v\n", protoFile)
	}
}
Output:
Proto file: service.proto

type ErrorCode

type ErrorCode string

ErrorCode represents a category of errors.

const (
	// ErrUnknown represents an unknown error.
	ErrUnknown ErrorCode = "UNKNOWN"

	// ErrInternal represents an internal error.
	ErrInternal ErrorCode = "INTERNAL"

	// ErrInvalidInput represents invalid input.
	ErrInvalidInput ErrorCode = "INVALID_INPUT"

	// ErrInvalidArgument represents invalid argument passed to a function.
	ErrInvalidArgument ErrorCode = "INVALID_ARGUMENT"

	// ErrNotFound represents a resource not found error.
	ErrNotFound ErrorCode = "NOT_FOUND"

	// ErrAlreadyExists represents a resource already exists error.
	ErrAlreadyExists ErrorCode = "ALREADY_EXISTS"

	// ErrPermissionDenied represents a permission denied error.
	ErrPermissionDenied ErrorCode = "PERMISSION_DENIED"

	// ErrTimeout represents a timeout error.
	ErrTimeout ErrorCode = "TIMEOUT"

	// ErrCanceled represents a canceled operation.
	ErrCanceled ErrorCode = "CANCELED"

	// Configuration errors
	ErrConfig         ErrorCode = "CONFIG_ERROR"
	ErrConfigNotFound ErrorCode = "CONFIG_NOT_FOUND"
	ErrConfigInvalid  ErrorCode = "CONFIG_INVALID"

	// Proto file errors
	ErrProtoNotFound ErrorCode = "PROTO_NOT_FOUND"
	ErrProtoInvalid  ErrorCode = "PROTO_INVALID"
	ErrProtoScan     ErrorCode = "PROTO_SCAN_ERROR"

	// Compilation errors
	ErrCompilation      ErrorCode = "COMPILATION_FAILED"
	ErrCompilerNotFound ErrorCode = "COMPILER_NOT_FOUND"
	ErrCompilerVersion  ErrorCode = "COMPILER_VERSION_ERROR"

	// Dependency errors
	ErrDependency  ErrorCode = "DEPENDENCY_ERROR"
	ErrCircularDep ErrorCode = "CIRCULAR_DEPENDENCY"
	ErrMissingDep  ErrorCode = "MISSING_DEPENDENCY"

	// Validation errors
	ErrValidation ErrorCode = "VALIDATION_ERROR"

	// IO errors
	ErrIO         ErrorCode = "IO_ERROR"
	ErrFileRead   ErrorCode = "FILE_READ_ERROR"
	ErrFileWrite  ErrorCode = "FILE_WRITE_ERROR"
	ErrFileDelete ErrorCode = "FILE_DELETE_ERROR"

	// Cache errors
	ErrCache      ErrorCode = "CACHE_ERROR"
	ErrCacheRead  ErrorCode = "CACHE_READ_ERROR"
	ErrCacheWrite ErrorCode = "CACHE_WRITE_ERROR"

	// Plugin errors
	ErrPlugin        ErrorCode = "PLUGIN_ERROR"
	ErrPluginLoad    ErrorCode = "PLUGIN_LOAD_ERROR"
	ErrPluginExecute ErrorCode = "PLUGIN_EXECUTE_ERROR"
)

Common error codes used throughout Buffalo.

func (ErrorCode) String

func (c ErrorCode) String() string

String returns the string representation of the error code.

Jump to

Keyboard shortcuts

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