exceptions

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: Apache-2.0 Imports: 2 Imported by: 0

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

func Panicf(format string, args ...any)

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.

Jump to

Keyboard shortcuts

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