recovery

package
v0.0.0-...-9392aba Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2024 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package recover provides Recover and Safe

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Recover

func Recover(value any) error

Recover returns an error that represents an error caught from recover. When passed nil, returns nil.

It should be used as:

if err := Recover(recover()); err != nil {
	// ... handle here ...
}

func Safe

func Safe[T any](f func() (T, error)) (t T, err error)

Safe calls and returns the value of f. If a panic occurs, t is set to the zero value, and error as returned by Recover.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/tkw1536/pkglib/recovery"
)

func main() {
	// a function that doesn't return an error is invoked normally
	fmt.Println(
		recovery.Safe(func() (int, error) {
			return 42, nil
		}),
	)

	fmt.Println(
		recovery.Safe(func() (int, error) {
			return 0, errors.New("some error")
		}),
	)

	{
		res, err := recovery.Safe(func() (int, error) {
			panic("test panic")
		})

		fmt.Printf("%d %#v\n", res, err)
	}
}
Output:

42 <nil>
0 some error
0 recovery.recovered{/* recover() = "test panic" */}

func Safe2

func Safe2[S, T any](f func() (S, T, error)) (s S, t T, err error)

Safe2 is like Safe, but takes a function returning two values.

Types

This section is empty.

Jump to

Keyboard shortcuts

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