errors

package
v0.2.0 Latest Latest
Warning

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

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

Documentation

Overview

Package errors はプロジェクト全体のエラーハンドリングと警告システムを提供します。 scikit-learnの警告・例外システムにインスパイアされており、構造化されたエラー情報を提供します。

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 はエラーが特定の型にキャスト可能かどうかを判定します。

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 はエラーが特定のターゲットエラーかどうかを判定します。

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 は新しいエラーを作成します。

func NewDimensionError

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

NewDimensionError は新しいDimensionErrorを作成し、スタックトレースを付与します。

func NewInputShapeError

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

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

func NewModelError

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

NewModelError は新しいModelErrorを作成し、スタックトレースを付与します。

func NewNotFittedError

func NewNotFittedError(modelName, method string) error

NewNotFittedError は新しいNotFittedErrorを作成し、スタックトレースを付与します。

func NewNumericalInstabilityError

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

NewNumericalInstabilityError は新しいNumericalInstabilityErrorを作成します。

func NewValidationError

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

NewValidationError は新しいValidationErrorを作成し、スタックトレースを付与します。

func NewValueError

func NewValueError(op, message string) error

NewValueError は新しいValueErrorを作成し、スタックトレースを付与します。

func Newf

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

Newf は新しいフォーマット済みエラーを作成します。

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 はGoMLライブラリ全体の警告ハンドラを設定します。 これにより、ConvergenceWarningなどのカスタム警告の処理方法を制御できます。

例:

errors.SetWarningHandler(func(w error) {
    // 警告を無視する
})

func SetZerologWarnFunc

func SetZerologWarnFunc(warnFunc func(warning error))

SetZerologWarnFunc はzerolog警告関数を設定します(循環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 は警告を発生させます。 zerologが利用可能な場合は構造化ログとして出力し、そうでなければ従来のハンドラを使用します。

func WithStack

func WithStack(err error) error

WithStack はエラーにスタックトレースを付与します。

func Wrap

func Wrap(err error, message string) error

Wrap は既存のエラーをメッセージ付きでラップします。

func Wrapf

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

Wrapf は既存のエラーをフォーマット文字列でラップします。

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 は最適化アルゴリズムが収束しなかった場合に発生する警告です。

func NewConvergenceWarning

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

NewConvergenceWarning は新しいConvergenceWarningを作成します。

func (*ConvergenceWarning) Error

func (w *ConvergenceWarning) Error() string

func (*ConvergenceWarning) MarshalZerologObject

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

MarshalZerologObject はzerologのイベントに構造化された警告情報を追加します。

type DataConversionWarning

type DataConversionWarning struct {
	FromType string
	ToType   string
	Reason   string
}

DataConversionWarning はデータの型が暗黙的に変換された場合に発生する警告です。

func NewDataConversionWarning

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

NewDataConversionWarning は新しいDataConversionWarningを作成します。

func (*DataConversionWarning) Error

func (w *DataConversionWarning) Error() string

func (*DataConversionWarning) MarshalZerologObject

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

MarshalZerologObject はzerologのイベントに構造化された警告情報を追加します。

type DimensionError

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

DimensionError は入力データの次元が期待値と異なる場合のエラーです。

func (*DimensionError) Error

func (e *DimensionError) Error() string

func (*DimensionError) MarshalZerologObject

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

MarshalZerologObject はzerologのイベントに構造化されたエラー情報を追加します。

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 は機械学習モデルに関する一般的なエラーです。

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 はモデルが未学習の状態で `Predict` や `Transform` を呼び出した場合のエラーです。

func (*NotFittedError) Error

func (e *NotFittedError) Error() string

func (*NotFittedError) MarshalZerologObject

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

MarshalZerologObject はzerologのイベントに構造化されたエラー情報を追加します。

type NumericalInstabilityError

type NumericalInstabilityError struct {
	Operation string                 // 発生した操作(例: "gradient_update", "loss_calculation")
	Values    []float64              // 問題のある値
	Context   map[string]interface{} // デバッグ用の追加コンテキスト情報
	Iteration int                    // 発生したイテレーション番号
}

NumericalInstabilityError は数値計算が不安定になった場合のエラーです。 NaN、Inf、オーバーフロー、アンダーフローなどを検出します。

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 // この条件で返される値
}

UndefinedMetricWarning は評価指標が計算できない場合に発生する警告です。 例えば、適合率(precision)を計算する際に、陽性クラスの予測が一つもなかった場合など。

func NewUndefinedMetricWarning

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

NewUndefinedMetricWarning は新しいUndefinedMetricWarningを作成します。

func (*UndefinedMetricWarning) Error

func (w *UndefinedMetricWarning) Error() string

type ValidationError

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

ValidationError は入力パラメータの検証に失敗した場合のエラーです。 `ValueError`よりも具体的なバリデーションロジックの失敗を示します。

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) MarshalZerologObject

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

MarshalZerologObject はzerologのイベントに構造化されたエラー情報を追加します。

type ValueError

type ValueError struct {
	Op      string
	Message string
}

ValueError は引数の値が不適切または不正な場合に発生するエラーです。 例えば、`log`関数に負の数を渡した場合など。

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