Documentation
¶
Overview ¶
Package exceptions provides helper functions to leverage Go's `panic`, `recover` and `defer` as an "exceptions" system.
The `panic`, `recover` and the added runtime type checking is slow when compared to simply returning errors. So it should be used where a little latency in case of errors is not an issue.
It defines `Try` and `TryCatch[E any]`.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Panicf ¶
Panicf is a shortcut to `panic(errors.Errorf(format, args...))`. It throws an error with a stack-trace and the formatted message.
func Try ¶
func Try(fn func()) (exception any)
Try calls `fn` and return any exception (`panic`) that may occur.
Runtime panics are converted to an error with a stack-trace, to facilitate debugging.
Example:
var x ResultType e := Try(func() { x = DoSomething() }) if e != nil { if eInt, ok := e.(int); ok { errorInt = e } else if err, ok := e.(err); ok { klog.Errorf("%v", e) } else { panic(e) } }
func TryCatch ¶
func TryCatch[E any](fn func()) (exception E)
TryCatch executes `fn` and in case of `panic`, it recovers if of the type `E`. For a `panic` of any other type, it simply re-throws the `panic`.
Runtime panics are converted to errors.Error, with a stack trace.
Example:
var x ResultType err := TryCatch[error](func() { x = DoSomething() }) if err != nil { // Handle error ... }
Types ¶
This section is empty.