exceptions

package
v0.8.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2023 License: Apache-2.0 Imports: 1 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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.

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`.

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