Documentation
¶
Index ¶
- Variables
- func CatchFailure(set func(err error))
- func ExtractContext(err error) context.Context
- func IsContextError(err error) bool
- func LogStats(logger ErrorStatsLogger)
- func ResetMetrics()
- type BasicIrr
- func (ir *BasicIrr) ClosestCode() int64
- func (ir *BasicIrr) CurrentCode() int64
- func (ir *BasicIrr) Error() string
- func (ir *BasicIrr) GetCode() int64
- func (ir *BasicIrr) GetCodeStr() string
- func (ir *BasicIrr) GetTag(key string) (val []string)
- func (ir *BasicIrr) GetTraceInfo() *traceInfo
- func (ir *BasicIrr) HasAnyCode() bool
- func (ir *BasicIrr) HasCurrentCode() bool
- func (ir *BasicIrr) LogError(logger IErrorLogger) IRR
- func (ir *BasicIrr) LogFatal(logger IFatalLogger) IRR
- func (ir *BasicIrr) LogWarn(logger IWarnLogger) IRR
- func (ir *BasicIrr) NearestCode() int64
- func (ir *BasicIrr) Root() error
- func (ir *BasicIrr) RootCode() int64
- func (ir *BasicIrr) SetCode(val int64) IRR
- func (ir *BasicIrr) SetTag(key, val string)
- func (ir *BasicIrr) Source() (err error)
- func (ir *BasicIrr) ToString(printTrace bool, split string) string
- func (ir *BasicIrr) TraverseCode(fn func(err error, code int64) error) (err error)
- func (ir *BasicIrr) TraverseToRoot(fn func(err error) error) (err error)
- func (ir *BasicIrr) TraverseToSource(fn func(err error, isSource bool) error) (err error)
- func (ir *BasicIrr) Unwrap() error
- type ContextualError
- func ErrorWithContext(ctx context.Context, formatOrMsg string, args ...any) ContextualError
- func TraceWithContext(ctx context.Context, formatOrMsg string, args ...any) ContextualError
- func TrackWithContext(ctx context.Context, innerErr error, formatOrMsg string, args ...any) ContextualError
- func WrapWithContext(ctx context.Context, innerErr error, formatOrMsg string, args ...any) ContextualError
- type ContextualIrr
- func (ce *ContextualIrr) Context() context.Context
- func (ce *ContextualIrr) ToString(printTrace bool, split string) string
- func (ce *ContextualIrr) WithContext(ctx context.Context) ContextualError
- func (ce *ContextualIrr) WithDeadline(deadline time.Time) ContextualError
- func (ce *ContextualIrr) WithTimeout(timeout time.Duration) ContextualError
- func (ce *ContextualIrr) WithValue(key, val interface{}) ContextualError
- type ErrorMetrics
- type ErrorStatsLogger
- type ICodeGetter
- type ICodeManager
- type ICoder
- type IErrorLogger
- type IFatalLogger
- type ILogCaller
- type IRR
- func Error(formatOrMsg string, args ...any) IRR
- func ErrorC[T int64](code T, formatOrMsg string, args ...any) IRR
- func Trace(formatOrMsg string, args ...any) IRR
- func TraceSkip(skip int, formatOrMsg string, args ...any) IRR
- func Track(innerErr error, formatOrMsg string, args ...any) IRR
- func TrackSkip(skip int, innerErr error, formatOrMsg string, args ...any) IRR
- func Wrap(innerErr error, formatOrMsg string, args ...any) IRR
- type ITagger
- type ITraverseCoder
- type ITraverseError
- type ITraverseIrr
- type IUnwrap
- type IWarnLogger
- type Spawner
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrUntypedExecutionFailure = errors.New("!!!panic")
Functions ¶
func CatchFailure ¶
func CatchFailure(set func(err error))
CatchFailure is used to catch and handle panics within a function, preventing them from causing the program to crash while unifying the encapsulation of non-error information. It is declared at the beginning of a function with the defer keyword, ensuring that any panic during function execution can be caught. This function takes a callback function as a parameter, which is called when a panic occurs to handle the recovered error.
Usage example:
// A sample function that may cause panic
func riskyOperation() (err error) {
// Defer calling CatchFailure at the start of riskyOperation
// to ensure any subsequent panics can be caught and handled
defer irr.CatchFailure(func(e error) {
// Convert the recovered panic into a regular error so the function can return it
// err can be set as a side effect, or the caught e can be handled directly (e.g., logging)
// If the panic parameter is nil, e will be nil
// If the panic is triggered with an error, the corresponding err will be passed directly
// If the panic is another value, ErrUntypedExecutionFailure will be passed in, with the panic value attached to the error message
err = e
})
// Trigger an out-of-bounds error that will cause a panic
_ = make([]int, 0)[1]
// Due to the panic above, the following code will not execute
fmt.Println("This line of code will not be executed.")
// If there is no panic, the function will return a nil error
return nil
}
// Calling riskyOperation elsewhere, handling errors returned by it
func main() {
if err := riskyOperation(); err != nil {
fmt.Printf("Caught error: %v\n", err)
} else {
fmt.Println("Operation successful, no errors occurred")
}
}
Note: CatchFailure should only be used to deal with panics caused by unforeseen situations, while regular error handling should be done using the error.
Types ¶
type BasicIrr ¶
type BasicIrr struct {
Code int64 `json:"code"`
Msg string `json:"msg"`
Trace *traceInfo `json:"trace"`
// contains filtered or unexported fields
}
func (*BasicIrr) ClosestCode ¶
ClosestCode 返回最近的有效错误码 Deprecated: 使用 NearestCode() 获得更清晰的语义
func (*BasicIrr) CurrentCode ¶
CurrentCode 返回当前错误对象的错误码(可能为0)
func (*BasicIrr) GetCodeStr ¶
GetCodeStr Determines how the code is written to the message, so that this method can input an empty string to avoid outputting the code in the message
func (*BasicIrr) GetTraceInfo ¶
func (ir *BasicIrr) GetTraceInfo() *traceInfo
func (*BasicIrr) HasCurrentCode ¶
HasCurrentCode 检查当前错误对象是否显式设置了错误码
func (*BasicIrr) LogError ¶
func (ir *BasicIrr) LogError(logger IErrorLogger) IRR
LogError the implementation of ILogCaller
func (*BasicIrr) LogFatal ¶
func (ir *BasicIrr) LogFatal(logger IFatalLogger) IRR
LogFatal the implementation of ILogCaller
func (*BasicIrr) LogWarn ¶
func (ir *BasicIrr) LogWarn(logger IWarnLogger) IRR
LogWarn the implementation of ILogCaller
func (*BasicIrr) NearestCode ¶
NearestCode 返回错误链中最近的有效错误码(非零) 这是推荐使用的方法,符合用户直觉
func (*BasicIrr) ToString ¶
ToString consecutive equal codes will be printed only once during the traceback process
func (*BasicIrr) TraverseCode ¶
TraverseCode the implementation of ITraverseCoder[int64]
func (*BasicIrr) TraverseToRoot ¶
TraverseToRoot the implementation of ITraverseError
func (*BasicIrr) TraverseToSource ¶
TraverseToSource the implementation of ITraverseIrr
type ContextualError ¶
type ContextualError interface {
IRR
Context() context.Context
WithContext(ctx context.Context) ContextualError
WithDeadline(deadline time.Time) ContextualError
WithTimeout(timeout time.Duration) ContextualError
WithValue(key, val interface{}) ContextualError
}
ContextualError 带上下文的错误接口
func ErrorWithContext ¶
func ErrorWithContext(ctx context.Context, formatOrMsg string, args ...any) ContextualError
ErrorWithContext 创建带上下文的错误
func TraceWithContext ¶
func TraceWithContext(ctx context.Context, formatOrMsg string, args ...any) ContextualError
TraceWithContext 创建带堆栈跟踪和上下文的错误
func TrackWithContext ¶
func TrackWithContext(ctx context.Context, innerErr error, formatOrMsg string, args ...any) ContextualError
TrackWithContext 包装错误并添加堆栈跟踪和上下文
func WrapWithContext ¶
func WrapWithContext(ctx context.Context, innerErr error, formatOrMsg string, args ...any) ContextualError
WrapWithContext 包装错误并添加上下文
type ContextualIrr ¶
type ContextualIrr struct {
*BasicIrr
// contains filtered or unexported fields
}
ContextualIrr 实现了带上下文的错误
func (*ContextualIrr) ToString ¶
func (ce *ContextualIrr) ToString(printTrace bool, split string) string
ToString 重写以包含上下文信息
func (*ContextualIrr) WithContext ¶
func (ce *ContextualIrr) WithContext(ctx context.Context) ContextualError
WithContext 使用新的上下文创建副本
func (*ContextualIrr) WithDeadline ¶
func (ce *ContextualIrr) WithDeadline(deadline time.Time) ContextualError
WithDeadline 设置截止时间
func (*ContextualIrr) WithTimeout ¶
func (ce *ContextualIrr) WithTimeout(timeout time.Duration) ContextualError
WithTimeout 设置超时时间
func (*ContextualIrr) WithValue ¶
func (ce *ContextualIrr) WithValue(key, val interface{}) ContextualError
WithValue 添加键值对
type ErrorMetrics ¶
type ErrorMetrics struct {
// 错误创建统计
ErrorCreated int64 `json:"error_created"`
ErrorWithCode int64 `json:"error_with_code"`
ErrorWithTrace int64 `json:"error_with_trace"`
ErrorWrapped int64 `json:"error_wrapped"`
// 错误遍历统计
TraverseOps int64 `json:"traverse_ops"`
// 时间统计
LastErrorTime time.Time `json:"last_error_time"`
// 错误码统计
CodeStats map[int64]int64 `json:"code_stats"`
// contains filtered or unexported fields
}
ErrorMetrics 错误统计信息
type ErrorStatsLogger ¶
type ErrorStatsLogger interface {
LogErrorStats(metrics *ErrorMetrics)
}
ErrorStatsLogger 错误统计日志接口
type ICodeGetter ¶
type ICodeManager ¶
type ICodeManager[TCode any] interface { // 错误码获取 NearestCode() TCode // 最近的有效错误码 CurrentCode() TCode // 当前对象的错误码 RootCode() TCode // 根错误的错误码 // 错误码状态检查 HasCurrentCode() bool // 当前对象是否设置了错误码 HasAnyCode() bool // 错误链中是否有任何错误码 // 向后兼容(标记为废弃) GetCode() TCode // @deprecated: 使用 NearestCode() ClosestCode() TCode // @deprecated: 使用 NearestCode() }
新的清晰错误码API接口
type IErrorLogger ¶
type IErrorLogger interface{ Error(args ...any) }
type IFatalLogger ¶
type IFatalLogger interface{ Fatal(args ...any) }
type ILogCaller ¶
type ILogCaller interface {
LogWarn(logger IWarnLogger) IRR
LogError(logger IErrorLogger) IRR
LogFatal(logger IFatalLogger) IRR
}
type IRR ¶
type IRR interface {
ITraverseIrr
error
ITraverseError
IUnwrap
ICodeManager[int64] // 使用新的清晰错误码API
SetCode(val int64) IRR // 保留SetCode方法
GetCodeStr() string // 保留GetCodeStr方法
ITraverseCoder[int64]
ITagger
ILogCaller
ToString(printTrace bool, split string) string
GetTraceInfo() *traceInfo
}
func Error ¶
Error creates a new IRR error object with a formatted message. formatOrMsg is a string that accepts printf style format specifiers. args are variadic parameters that represent the arguments for the formatting string.
Example ¶
package main
import (
"fmt"
"github.com/khicago/irr"
)
func main() {
err := irr.Error("this is a new error")
errWithParam := irr.Error("this is a new error with integer %d", 1)
fmt.Println(err)
fmt.Println(errWithParam)
}
Output: this is a new error this is a new error with integer 1
func ErrorC ¶
ErrorC creates a new IRR error object with an error code and a formatted message. code is an int64 type error code used to identify and classify errors. formatOrMsg is a string that accepts printf style format specifiers to generate the error message. args are variadic parameters that represent the arguments for the formatting string. It returns an IRR error object set with the specific error code.
Usage example:
// Define a sample error code const ErrCodeInvalidInput int64 = 1001
// ValidateInput checks the input string and returns an error if it is empty
func ValidateInput(input string) error {
if input == "" {
// Create an error object with a specific error code and formatted message using ErrorC
return irr.ErrorC(ErrCodeInvalidInput, "validation failed: %s", "input cannot be empty")
}
// Other input validation logic...
return nil
}
Note: ErrorC is typically used when you wish to categorize errors or define specific status codes for easier error handling and response later on.
func Trace ¶
Trace creates an error object with stack trace and a formatted message. formatOrMsg is a string that accepts printf style format specifiers. args are variadic parameters that represent the arguments for the formatting string. It defaults to skipping one call frame, usually the place where Trace is called.
Example ¶
package main
import (
"fmt"
"github.com/khicago/irr"
)
func main() {
err := irr.Trace("this is a new error")
errWithParam := irr.Trace("this is a new error with integer %d", 1)
fmt.Println(err.ToString(true, ""))
fmt.Println(errWithParam.ToString(true, ""))
wrappedErr := irr.Track(err, "some wrap information")
wrappedErrWithParam := irr.Track(err, "some wrap information with integer %d", 1)
fmt.Println(wrappedErr.ToString(true, " && "))
fmt.Println(wrappedErrWithParam.ToString(true, "\n"))
}
func TraceSkip ¶
TraceSkip creates an error object with stack trace and formatted message, skipping a certain number of stack frames. skip indicates the number of call frames to skip in the stack trace. formatOrMsg is a string that accepts printf style format specifiers. args are variadic parameters that represent the arguments for the formatting string.
func Track ¶
Track creates an error object with a stack trace and wraps an inner error. innerErr is the error being wrapped. formatOrMsg is a string that accepts printf style format specifiers. args are variadic parameters that represent the arguments for the formatting string. It defaults to skipping one call frame, starting the trace where Track is called.
func TrackSkip ¶
TrackSkip creates an error object with a stack trace and wraps an inner error, skipping a specified number of stack frames. skip indicates the number of call frames to skip in the stack trace. innerErr is the error being wrapped. formatOrMsg is a string that accepts printf style format specifiers. args are variadic parameters that represent the arguments for the formatting string.
func Wrap ¶
Wrap wraps an existing error object with a given message and an inner error. innerErr is the error being wrapped. formatOrMsg is a string that accepts printf style format specifiers. args are variadic parameters that represent the arguments for the formatting string.
Example ¶
package main
import (
"fmt"
"github.com/khicago/irr"
)
func main() {
err := fmt.Errorf("default err message")
wrappedErr := irr.Wrap(err, "some wrap information")
wrappedErrWithParam := irr.Wrap(err, "some wrap information with integer %d", 1)
fmt.Println(wrappedErr)
fmt.Println(wrappedErrWithParam)
}
Output: some wrap information, default err message some wrap information with integer 1, default err message
Example (CustomPrint) ¶
package main
import (
"fmt"
"github.com/khicago/irr"
)
func main() {
err := fmt.Errorf("default err message")
wrappedErr := irr.Wrap(err, "some wrap information")
wrappedErrWithParam := irr.Wrap(err, "some wrap information with integer %d", 1)
fmt.Println(wrappedErr.ToString(false, " ==> "))
fmt.Println(wrappedErrWithParam.ToString(false, " ==> "))
}
Output: some wrap information ==> default err message some wrap information with integer 1 ==> default err message
type ITraverseCoder ¶
type ITraverseError ¶
type ITraverseIrr ¶
type IWarnLogger ¶
type IWarnLogger interface{ Warn(args ...any) }
type Spawner ¶
type Spawner interface {
Error(formatOrMsg string, args ...interface{}) IRR
Wrap(innerErr error, formatOrMsg string, args ...interface{}) IRR
TraceSkip(skip int, formatOrMsg string, args ...interface{}) IRR
Trace(formatOrMsg string, args ...interface{}) IRR
TrackSkip(skip int, innerErr error, formatOrMsg string, args ...interface{}) IRR
Track(innerErr error, formatOrMsg string, args ...interface{}) IRR
}