fail

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 4 Imported by: ? 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.

README

fail — wrappers around os.Exit with printing abilities

fail is a tiny library of routines, which print some user-defined information and immediately call to function os.Exit from the standard library of Go. It is aimed to reduce cumbersome constructions of preparation stages of tests. CLI applications also could benefit from the calls to its routines.

The library provides functions IfErr and Now, which offer, correspondingly, conditional and unconditional termination of program after they print reason of the stop. The functions wrap around calls to method Term of type T. The type allows to control finely format of the messages, select output stream and choose exit status code.

Usage

The purpose of the library is to remove cluttering in tests, which appears, for example, in the following form:

import (
	"fmt"
	"os"
	"testing"
)

func prepareDirectoryAndFiles() {
	err := os.Mkdir("/path/to/dir", 0666)
	if err != nil {
		fmt.Printf("can't create directory: %v", err)
		os.Exit(1)
	}
	file, err := os.Create("/path/to/file")
	if err != nil {
		fmt.Printf("can't create file: %v", err)
		os.Exit(1)
	}
	…
}

func TestSomeOp(t *testing.T) {
	prepareDirectoryAndFiles()
	…
}

func TestSomeOtherOp(t *testing.T) {
	prepareDirectoryAndFiles()
	…
}

It is easy to see, that there is no need to return the happened error like usually, as the tests can't be launched, if the preparation stage has failed. So, the routine prepareDirectoryAndFiles just prints the error and exits immediately. A similar situation can be found in CLI applications, where early termination after a curt message is preferrable in main functions or subcommand routines:

import (
	"fmt"
	"os"
)

func main() {
	data, err := os.ReadFile("/path/to/file")
	if err != nil {
		fmt.Printf("can't read file: %v", err)
		os.Exit(1)
	}
	…
}

The repeatable lines of the error processing clog the functions. Thing is, the specific messages are not very important, it's enough to output the reasons of termination in some generic form before the termination. Here, the routines of the library could help. Conditional termination is the most demanded feature, and it's covered by function IfErr. The example above with function main could be refactored with its help in the following way:

import (
	"fmt"
	"os"

	"codeberg.org/alex-ilchukov/fail"
)

func main() {
	data, err := os.ReadFile("/path/to/file")
	fail.IfErr(err, "os.ReadFile")
	…
}

The function would message something like "main.main: os.ReadFile: <err>" in case, when err is not nil, displaying the description of the error value. Sometimes though (for example, when there is a condition, but it's not set up around error values), it's sister-function Now would be preferrable:

import (
	"runtime"

	"codeberg.org/alex-ilchukov/fail"
)

func Line() int {
	_, _, line, proper := runtime.Caller(1)
	if !proper {
		fail.Now("call to runtime.Caller has been improper")
	}
	return line
}

func CastToMyInterface(v any) MyInterface {
	i, ok := v.(MyInterface)
	if !ok {
		fail.Now("can't cast argument to MyInterface")
	}
	return i
}

The last function CastToMyInterface can't provide detailed information on the failed argument. Indeed, format of the messages of functions IfErr and Now is fixed, which is also true for the facts, that they output to os.Stdout and terminate the program with status code 1. Nevertheless, the limitations could be overcome with use of type T, which method T.Term is used by the library functions under the hood. The type allows to specify format of the messages, writer to print the messages to, and exit status code. With T the function in question could be refactored in the following way:

import (
	"os"

	"codeberg.org/alex-ilchukov/fail"
)

func CastToMyInterface(v any) MyInterface {
	i, ok := v.(MyInterface)
	if !ok {
		fail.T{Format: "can't cast %[2]v to MyInterface"}.Term(v)
	}
	return i
}

It should be mentioned, that T.Term always supplies name of the caller as its first parameter to the format routines of package fmt from the standard libray, so that's the reason for appearance of %[2]v in the format string. Of course, with such a format string, the information of the caller function would be omitted from the output.

Type T also allows to control over which caller function should be displayed in the output. Its field T.CallerSkip is interpreted by the method T.Term as amount of intermediate functions to skip before obtaining the name of the caller. Default value of zero for the field means displaying of the direct caller of the method. Thus, for the example above, if only %[1]s appeared in the format string, name CastToMyInterface would be used.

License

The library is licensed under MIT license.

Documentation

Overview

Package fail provides routines IfErr and Now, which print some user-defined information and immediately terminate the program either conditionally (for the former function) or unconditionally (for the latter). Both functions take a reason of termination, print it to the standard output along with name of the caller function, and exit with status code 1. IfErr also outputs provided error value.

The package provides more low-level layer in form of type T and its method T.Term. The type allows to set up format of the message, writer to write the messages to, and exit status code. It also allows to specify amount of intermediate functions to skip before finding of the caller.

Index

Constants

View Source
const Version = "v1.0.0"

Version of the library

Variables

This section is empty.

Functions

func IfErr

func IfErr(err error, reason any)

IfErr takes an error value and a reason to terminate the program. It does nothing, if the error value is nil, but otherwise it prints the caller of the function with the reason and error value to os.Stdout and terminates the program with code 1

func Now

func Now(reason any)

Now takes a reason to terminate the program, prints the caller of the function with the reason to os.Stdout and terminates the program with code 1

Types

type T

type T struct {
	// CallerSkip is the base value, from which an argument to a call of
	// the function [runtime.Caller] is calculated to obtain data on files
	// and lines of callers of method [T.Term]. The calculations are made
	// in such a way, that zero value of the field results in getting of
	// data on direct callers of the method. If the method is called via
	// intermediate functions, the field should be set up to the amount of
	// these functions. For example, if a user wishes to call to [T.Term]
	// via just one intermediate function, they should set up 1 as the
	// field's value.
	CallerSkip int

	// Writer is the endpoint for output. It is allowed to be nil, though,
	// the printing is skipped in such a case.
	Writer io.Writer

	// Format is a format string, formed with the syntax of [fmt.Printf].
	// It is used to create an output string. The format is supposed to
	// support name of the caller as its first parameter.
	Format string

	// Code is the status code to terminate the program with
	Code int
}

T is a type of terminating contexts. The type encapsulates basic technical information and provides method T.Term to properly terminate a program.

func (T) Term

func (t T) Term(args ...any)

Term writes name of the caller, obtained with T.CallerSkip, with the provided arguments to T.Writer accordingly to T.Format, if the writer is not nil, and then terminates the program with status code T.Code

Jump to

Keyboard shortcuts

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