errors

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package errors provides error handling and warning systems for the entire project. Inspired by scikit-learn's warning and exception system, it provides structured error information.

Example

Example demonstrates Go 1.13+ error wrapping

package main

import (
	"errors"
	"fmt"
)

func main() {
	// Create a base error
	baseErr := fmt.Errorf("invalid input value")

	// Wrap the error with context using Go 1.13+ syntax
	wrappedErr := fmt.Errorf("model validation failed: %w", baseErr)

	// Further wrap with operation context
	opErr := fmt.Errorf("LinearRegression.Fit: %w", wrappedErr)

	// Use errors.Is to check for specific error types
	if errors.Is(opErr, baseErr) {
		fmt.Println("Found base error in chain")
	}

	// Unwrap errors to get the underlying cause
	unwrapped := errors.Unwrap(opErr)
	fmt.Printf("Unwrapped: %v\n", unwrapped)

}
Output:

Found base error in chain
Unwrapped: model validation failed: invalid input value
Example (CustomErrorTypes)

Example_customErrorTypes demonstrates custom error type handling

package main

import (
	"errors"
	"fmt"

	scigoErrors "github.com/YuminosukeSato/scigo/pkg/errors"
)

func main() {
	// Create a custom error using our error constructors
	dimErr := scigoErrors.NewDimensionError("Transform", 5, 3, 1)

	// Wrap it with additional context
	wrappedErr := fmt.Errorf("preprocessing failed: %w", dimErr)

	// Check if error is of specific type using errors.As
	var dimensionErr *scigoErrors.DimensionError
	if errors.As(wrappedErr, &dimensionErr) {
		fmt.Printf("Dimension error: expected %d, got %d\n",
			dimensionErr.Expected, dimensionErr.Got)
	}

}
Output:

Dimension error: expected 5, got 3
Example (ErrorChaining)

Example_errorChaining demonstrates practical error chaining in ML operations

package main

import (
	"errors"
	"fmt"
)

func main() {
	// Simulate a machine learning pipeline error
	simulateMLError := func() error {
		// Simulate data validation error
		dataErr := fmt.Errorf("invalid data format")

		// Wrap with preprocessing context
		prepErr := fmt.Errorf("data preprocessing failed: %w", dataErr)

		// Wrap with model training context
		trainErr := fmt.Errorf("model training failed: %w", prepErr)

		return trainErr
	}

	err := simulateMLError()

	// Print the full error chain
	fmt.Printf("Error: %v\n", err)

	// Walk through the error chain
	current := err
	level := 0
	for current != nil {
		fmt.Printf("Level %d: %v\n", level, current)
		current = errors.Unwrap(current)
		level++
	}

}
Output:

Error: model training failed: data preprocessing failed: invalid data format
Level 0: model training failed: data preprocessing failed: invalid data format
Level 1: data preprocessing failed: invalid data format
Level 2: invalid data format
Example (ErrorComparison)

Example_errorComparison demonstrates error comparison patterns

package main

import (
	"errors"
	"fmt"

	scigoErrors "github.com/YuminosukeSato/scigo/pkg/errors"
)

func main() {
	// Create different types of errors
	notFittedErr := scigoErrors.NewNotFittedError("LinearRegression", "Predict")
	valueErr := scigoErrors.NewValueError("StandardScaler", "negative values not supported")

	// Create a sentinel error for comparison
	var customErr = errors.New("custom processing error")
	wrappedCustom := fmt.Errorf("operation failed: %w", customErr)

	// Use errors.Is for sentinel error checking
	if errors.Is(wrappedCustom, customErr) {
		fmt.Println("Custom error detected")
	}

	// Use errors.As for type assertions
	var notFitted *scigoErrors.NotFittedError
	if errors.As(notFittedErr, &notFitted) {
		fmt.Printf("Model %s is not fitted for %s\n",
			notFitted.ModelName, notFitted.Method)
	}

	var valErr *scigoErrors.ValueError
	if errors.As(valueErr, &valErr) {
		fmt.Printf("Value error in %s: %s\n", valErr.Op, valErr.Message)
	}

}
Output:

Custom error detected
Model LinearRegression is not fitted for Predict
Value error in StandardScaler: negative values not supported
Example (ErrorLogging)

Example_errorLogging demonstrates structured error logging

package main

import (
	"fmt"
	"log"

	scigoErrors "github.com/YuminosukeSato/scigo/pkg/errors"
)

func main() {
	// Create a complex error with context
	baseErr := scigoErrors.NewModelError("SGD", "convergence failure",
		scigoErrors.ErrNotImplemented)

	// Wrap with operation context
	opErr := fmt.Errorf("online learning iteration 150: %w", baseErr)

	// Log different levels of detail
	log.Printf("Simple: %v", opErr)
	log.Printf("Detailed: %+v", opErr) // This would show stack trace with cockroachdb/errors

	// For production, you'd use structured logging
	fmt.Printf("Error occurred in online learning: %v\n", opErr)

}
Output:

Error occurred in online learning: online learning iteration 150: goml: SGD: convergence failure: not implemented

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotImplemented は機能が未実装の場合のエラーです。
	ErrNotImplemented = New("not implemented")

	// ErrEmptyData は空のデータが渡された場合のエラーです。
	ErrEmptyData = New("empty data")

	// ErrSingularMatrix は特異行列の場合のエラーです。
	ErrSingularMatrix = New("singular matrix")
)

Functions

func As

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

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

func CheckMatrix

func CheckMatrix(operation string, matrix interface{ At(int, int) float64 }, rows, cols, iteration int) error

CheckMatrix checks all values in a matrix for numerical instability.

func CheckNumericalStability

func CheckNumericalStability(operation string, values []float64, iteration int) error

CheckNumericalStability checks if values contain NaN or Inf and returns an error if numerical instability is detected.

func CheckScalar

func CheckScalar(operation string, value float64, iteration int) error

CheckScalar checks a single scalar value for numerical instability.

func ClipGradient

func ClipGradient(gradient []float64, maxNorm float64) []float64

ClipGradient clips gradient values to prevent explosion.

func ClipValue

func ClipValue(value, min, max float64) float64

ClipValue clips a value to the range [min, max].

func Is

func Is(err, target error) bool

Is reports whether err matches target.

func LogSumExp

func LogSumExp(values []float64) float64

LogSumExp computes log(sum(exp(values))) in a numerically stable way.

func New

func New(message string) error

New creates a new error.

func NewDimensionError

func NewDimensionError(op string, expected, got, axis int) error

NewDimensionError creates a new DimensionError with stack trace.

func NewInputShapeError

func NewInputShapeError(phase string, expected, got []int) error

NewInputShapeError は新しいInputShapeErrorを作成します。

func NewModelError

func NewModelError(op, kind string, err error) error

NewModelError creates a new ModelError with stack trace.

func NewNotFittedError

func NewNotFittedError(modelName, method string) error

NewNotFittedError creates a new NotFittedError with stack trace.

func NewNumericalInstabilityError

func NewNumericalInstabilityError(operation string, values []float64, iteration int) error

NewNumericalInstabilityError creates a new NumericalInstabilityError.

func NewValidationError

func NewValidationError(param, reason string, value interface{}) error

NewValidationError creates a new ValidationError with stack trace.

func NewValueError

func NewValueError(op, message string) error

NewValueError creates a new ValueError with stack trace.

func Newf

func Newf(format string, args ...interface{}) error

Newf creates a new formatted error.

func Recover

func Recover(err *error, operation string)

Recover is a utility function to be used with defer to recover from panics and convert them into errors. It includes stack trace information for debugging.

This function should be called with a pointer to the error return value of the function where it's used.

Usage:

func SomeMethod() (err error) {
    defer Recover(&err, "SomeMethod")
    // ... method implementation ...
    return nil
}

If a panic occurs, it will be converted to a PanicError and assigned to err. If the function already has an error, the panic information will be wrapped.

func SafeDivide

func SafeDivide(numerator, denominator float64) float64

SafeDivide performs division with protection against division by zero. Returns 0 if denominator is zero or close to zero.

func SafeExecute

func SafeExecute(operation string, fn func() error) (err error)

SafeExecute executes a function and recovers from any panic, converting it to an error. This is useful for wrapping dangerous operations that might panic.

Parameters:

  • operation: A descriptive name for the operation being performed
  • fn: The function to execute safely

Returns:

  • error: nil if successful, PanicError if panic occurred, or original error from fn

Example:

err := SafeExecute("matrix inversion", func() error {
    // ... potentially panicking code ...
    return someOperation()
})

func SetWarningHandler

func SetWarningHandler(handler func(w error))

SetWarningHandler sets the warning handler for the entire GoML library. This allows you to control how custom warnings like ConvergenceWarning are handled.

Example:

errors.SetWarningHandler(func(w error) {
    // Ignore warnings
})

func SetZerologWarnFunc

func SetZerologWarnFunc(warnFunc func(warning error))

SetZerologWarnFunc sets the zerolog warning function (to avoid circular import).

func StabilizeExp

func StabilizeExp(value float64) float64

StabilizeExp computes exp with protection against overflow. Clips the input to prevent exp from returning Inf.

func StabilizeLog

func StabilizeLog(value float64) float64

StabilizeLog computes log with protection against log(0). Returns log(max(value, epsilon)) where epsilon is a small positive number.

func Warn

func Warn(w error)

Warn raises a warning. If zerolog is available, it outputs as structured log, otherwise uses traditional handler.

func WithStack

func WithStack(err error) error

WithStack annotates err with a stack trace.

func Wrap

func Wrap(err error, message string) error

Wrap wraps an existing error with a message.

func Wrapf

func Wrapf(err error, format string, args ...interface{}) error

Wrapf wraps an existing error with a formatted message.

Types

type CatastrophicForgettingWarning

type CatastrophicForgettingWarning struct {
	OldPerformance float64 // 以前のパフォーマンス
	NewPerformance float64 // 現在のパフォーマンス
	DropRate       float64 // 性能低下率
	Metric         string  // 使用したメトリクス(例: "accuracy", "f1_score")
}

CatastrophicForgettingWarning は破滅的忘却が発生した可能性がある場合の警告です。

func NewCatastrophicForgettingWarning

func NewCatastrophicForgettingWarning(metric string, oldPerf, newPerf float64) *CatastrophicForgettingWarning

NewCatastrophicForgettingWarning は新しいCatastrophicForgettingWarningを作成します。

func (*CatastrophicForgettingWarning) Error

type ConvergenceWarning

type ConvergenceWarning struct {
	Algorithm  string
	Iterations int
	Message    string
}

ConvergenceWarning is a warning raised when optimization algorithms fail to converge.

func NewConvergenceWarning

func NewConvergenceWarning(algorithm string, iterations int, message string) *ConvergenceWarning

NewConvergenceWarning creates a new ConvergenceWarning.

func (*ConvergenceWarning) Error

func (w *ConvergenceWarning) Error() string

func (*ConvergenceWarning) MarshalZerologObject

func (w *ConvergenceWarning) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject adds structured warning information to zerolog events.

type DataConversionWarning

type DataConversionWarning struct {
	FromType string
	ToType   string
	Reason   string
}

DataConversionWarning is a warning raised when data types are implicitly converted.

func NewDataConversionWarning

func NewDataConversionWarning(from, to, reason string) *DataConversionWarning

NewDataConversionWarning creates a new DataConversionWarning.

func (*DataConversionWarning) Error

func (w *DataConversionWarning) Error() string

func (*DataConversionWarning) MarshalZerologObject

func (w *DataConversionWarning) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject adds structured warning information to zerolog events.

type DimensionError

type DimensionError struct {
	Op       string
	Expected int
	Got      int
	Axis     int // 0 for rows, 1 for columns/features
}

DimensionError is an error raised when input data dimensions don't match expected values.

func (*DimensionError) Error

func (e *DimensionError) Error() string

func (*DimensionError) MarshalZerologObject

func (e *DimensionError) MarshalZerologObject(event *zerolog.Event)

MarshalZerologObject adds structured error information to zerolog events.

type InputShapeError

type InputShapeError struct {
	Phase    string // "training", "prediction", "transform"
	Expected []int  // 期待される形状
	Got      []int  // 実際の形状
	Feature  string // 問題のある特徴量名(オプション)
}

InputShapeError は入力データの形状が期待と異なる場合のエラーです。 DimensionErrorより詳細で、訓練時と推論時の不整合を検出します。

func (*InputShapeError) Error

func (e *InputShapeError) Error() string

type ModelDriftWarning

type ModelDriftWarning struct {
	DriftScore float64 // ドリフトスコア(検出器により異なる)
	Threshold  float64 // 閾値
	Detector   string  // 使用したドリフト検出器(例: "DDM", "ADWIN")
	Action     string  // 推奨アクション("reset", "alert", "retrain")
	Timestamp  int64   // ドリフト検出時のタイムスタンプ(Unix時間)
}

ModelDriftWarning はモデルドリフトが検出された場合の警告です。

func NewModelDriftWarning

func NewModelDriftWarning(detector string, score, threshold float64, action string) *ModelDriftWarning

NewModelDriftWarning は新しいModelDriftWarningを作成します。

func (*ModelDriftWarning) Error

func (w *ModelDriftWarning) Error() string

type ModelError

type ModelError struct {
	Op   string
	Kind string
	Err  error
}

ModelError is a general error related to machine learning models.

func (*ModelError) Error

func (e *ModelError) Error() string

func (*ModelError) Unwrap

func (e *ModelError) Unwrap() error

type NotFittedError

type NotFittedError struct {
	ModelName string
	Method    string
}

NotFittedError is an error raised when calling `Predict` or `Transform` on an unfitted model.

func (*NotFittedError) Error

func (e *NotFittedError) Error() string

func (*NotFittedError) MarshalZerologObject

func (e *NotFittedError) MarshalZerologObject(event *zerolog.Event)

MarshalZerologObject adds structured error information to zerolog events.

type NumericalInstabilityError

type NumericalInstabilityError struct {
	Operation string                 // Operation where error occurred (e.g., "gradient_update", "loss_calculation")
	Values    []float64              // Problematic values
	Context   map[string]interface{} // Additional context for debugging
	Iteration int                    // Iteration number where error occurred
}

NumericalInstabilityError is an error raised when numerical computation becomes unstable. It detects NaN, Inf, overflow, underflow, etc.

func (*NumericalInstabilityError) Error

func (e *NumericalInstabilityError) Error() string

type PanicError

type PanicError struct {
	// PanicValue is the original value passed to panic()
	PanicValue interface{}

	// StackTrace contains the stack trace at the time of panic
	StackTrace string

	// Operation identifies where the panic was recovered
	Operation string
}

PanicError represents an error that was created from a recovered panic. It includes the original panic value and stack trace information.

func NewPanicError

func NewPanicError(operation string, panicValue interface{}) *PanicError

NewPanicError creates a new PanicError with the given operation context and panic value.

func (*PanicError) Error

func (e *PanicError) Error() string

Error implements the error interface for PanicError.

func (*PanicError) String

func (e *PanicError) String() string

String provides detailed information including stack trace.

func (*PanicError) Unwrap

func (e *PanicError) Unwrap() error

Unwrap returns nil as PanicError doesn't wrap another error by default.

type UndefinedMetricWarning

type UndefinedMetricWarning struct {
	Metric    string
	Condition string
	Result    float64 // Value returned under this condition
}

UndefinedMetricWarning is a warning raised when metrics cannot be calculated. For example, when calculating precision with no positive class predictions.

func NewUndefinedMetricWarning

func NewUndefinedMetricWarning(metric, condition string, result float64) *UndefinedMetricWarning

NewUndefinedMetricWarning creates a new UndefinedMetricWarning.

func (*UndefinedMetricWarning) Error

func (w *UndefinedMetricWarning) Error() string

type ValidationError

type ValidationError struct {
	ParamName string
	Reason    string
	Value     interface{}
}

ValidationError is an error raised when input parameter validation fails. It indicates more specific validation logic failures than `ValueError`.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) MarshalZerologObject

func (e *ValidationError) MarshalZerologObject(event *zerolog.Event)

MarshalZerologObject adds structured error information to zerolog events.

type ValueError

type ValueError struct {
	Op      string
	Message string
}

ValueError is an error raised when argument values are inappropriate or invalid. For example, passing negative numbers to a `log` function.

func (*ValueError) Error

func (e *ValueError) Error() string

Jump to

Keyboard shortcuts

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