[Talking-Golang (Go)] Errors

errors

error is a interface, here is its definition:

1
2
3
type error interface {
Error() string
}

Error without stack

The traditional error handling idiom in Go is roughly akin to

1
2
3
4
5
6
7
import "errors"

func hasError() {}
if err != nil {
return err
}
}

Func New, wrap, Unwrap, Is, As provided by errors package.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// main.go

package main

import (
"fmt"
"errors"
)

func main() {
// without stack
err := errors.New("error msg")
fmt.Printf("%+v\n", err) // error msg

// format error message without stack
err = errors.New(fmt.Sprintf("error %s", "msg"))
fmt.Printf("%+v\n", err) // error msg

// format error message without stack
err = fmt.Errorf("error %s", "msg")
fmt.Printf("%+v\n", err) // error msg
}

References

[1] errors - The Go Programming Language - https://golang.org/pkg/errors/

[2] errors | Effective Go - The Go Programming Language - https://golang.org/doc/effective_go#errors

[3] Working with Errors in Go 1.13 - The Go Blog - https://blog.golang.org/go1.13-errors

[4] Go by Example: Errors - https://gobyexample.com/errors