exit

package
v0.0.13-beta27 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2024 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Overview

Package exit provides an alternative to os.Exit(int).

Unlike os.Exit(int), exit.Return(int) will run deferred functions before terminating. It's effectively like a return from main(), except you can specify the exit code.

Defer a call to exit.Recover() or exit.RecoverAll() at the beginning of main(). Use exit.Return(int) to initiate an exit.

func main() {
	defer exit.Recover()
	defer cleanup()
	...
	if err != nil {
		// Return from main() with a non-zero exit code,
		// making sure to run deferred cleanup.
		exit.Return(1)
	}
	...
}

All functions deferred *after* defer exit.Recover()/RecoverAll() will be executed before the exit. This is why the defer for this package should be the first statement in main().

NOTE: This mechanism only works if exit.Return() is called from the same goroutine that deferred exit.Recover(). Usually this means Return() should only be used from within main(), or within functions that are only ever called from main(). See Recover() and Return() for more details.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Recover

func Recover()

Recover should be deferred as the first line of main(). It recovers the panic initiated by Return and converts it to a call to os.Exit. Any functions deferred after Recover in the main goroutine will be executed prior to exiting. Recover will re-panic anything other than the panic it expects from Return.

func RecoverAll

func RecoverAll()

RecoverAll can be deferred instead of Recover as the first line of main(). Instead of re-panicking, RecoverAll will absorb any panic and convert it to an error log entry with a stack trace, followed by a call to os.Exit(255).

func Return

func Return(code int)

Return initiates a panic that sends the return code to the deferred Recover, executing other deferred functions along the way. When the panic reaches Recover, the return code will be passed to os.Exit. This should only be called from the main goroutine.

Types

This section is empty.

Jump to

Keyboard shortcuts

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