The golang comes with a fair amount of functions end up returning errors like values.
The golang errors function looking like this:
1 2 3 4 5 | func (ex *StructExample) Function() (string, error) bytes, err := StructExample.Function() if err != nil { // this process the error of StructExample } |
You can use the errors package and that implements functions to manipulate errors.
The official golang example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | package main import ( "errors" "fmt" ) func main() { err := errors.New("emit macho dwarf: elf header corrupted") if err != nil { fmt.Print(err) } } |
You can see how it created the new custom errors using the New function:
1 | errors.New("You got a error !") |
The fmt package formats an error value by calling its Errorf() string method, see the example:
1 2 3 4 5 6 7 8 | package main import "fmt" func main() { err := fmt.Errorf("ordinary error") fmt.Printf("%#v\n", err) } |
You can add more information about the error using struct types and fields.
The error type is an interface type and can be used in this way.
1 2 3 | type error interface { Error() string } |
And an error variable represents any value that can describe itself as a string, see the example:
1 2 3 4 | type manyError struct { err string initials string } |