Documentation ¶
Overview ¶
Package errors provides primitives for simple error handling primitives.
Example ¶
package main import ( "fmt" ) func Function(val1 int, val2 string, val3 bool) (string, error) { var err error // check input params Check(&err, val1 > 0, "val1 must be greater than 0") Check(&err, len(val2) > 0, "val2 can't be empty") Check(&err, val3, "val3 should be 'true'") if err != nil { return "", err } return fmt.Sprintf("val1=%d, val2='%s', val3=%t", val1, val2, val3), nil } func main() { err := Error("error message") fmt.Println(err) // Output: error message err = Errorf("error message: %s", "reason") fmt.Println(err) // Output: error message: reason err = Wrap(err, "new error message") fmt.Println(err) // Output: new error message-> error message: reason err = Wrapf(err, "one more error message: %s", "another reason") fmt.Println(err) // Output: "one more error message: another reason-> new error message-> error message: reason // val1 is invalid _, err = Function(0, "text", true) if err != nil { fmt.Println(err) // Output: al1 must be greater than 0 } // val2 is invalid _, err = Function(10, "", true) if err != nil { fmt.Println(err) // Output: val2 can't be empty } // val3 is invalid _, err = Function(10, "text", false) if err != nil { fmt.Println(err)
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Check ¶
Check function raises error if condition is false. If *err is not nil (means error has raised early) function does nothing and returns immediately. Otherwise if case of cond is false functions create Error and puts to *err.
Example ¶
// get fake invalid value r := rand.New(rand.NewSource(15)) val := r.Intn(99) // check value var err error Check(&err, val > 100, "rand value must be more than 100") fmt.Println(err)
Output: rand value must be more than 100
func Checkf ¶
Checkf function raises error if condition is false. If *err is not nil (means error has raised early) function does nothing and returns immediately. Otherwise if case of cond is false functions create Error (format with parameters) and puts to *err.
Example ¶
// get fake invalid value r := rand.New(rand.NewSource(15)) val := r.Intn(99) // check value var err error Checkf(&err, val > 100, "rand value must be more than %d", 100) fmt.Println(err)
Output: rand value must be more than 100
func Error ¶
Error returns an error that formats as the given text.
Example ¶
err := Error("error message") fmt.Println(err)
Output: error message
func Errorf ¶
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
Example ¶
err := Errorf("error message: %s", "reason") fmt.Println(err)
Output: error message: reason
func Wrap ¶
Wrap wraps error and returns the string as a value that satisfies error.
Example ¶
err := Error("error message 1") err = Wrap(err, "error message 2") fmt.Println(err)
Output: error message 2-> error message 1
Types ¶
This section is empty.