package errors
import "errors"
Package errors implements functions to manipulate errors.
Code:play
Output:Example¶
package main
import (
"fmt"
"time"
)
// MyError is an error implementation that includes a time and message.
type MyError struct {
When time.Time
What string
}
func (e MyError) Error() string {
return fmt.Sprintf("%v: %v", e.When, e.What)
}
func oops() error {
return MyError{
time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
"the file system has gone away",
}
}
func main() {
if err := oops(); err != nil {
fmt.Println(err)
}
}
1989-03-15 22:30:00 +0000 UTC: the file system has gone away
Index ¶
- func As(err error, target interface{}) bool
- func Is(err, target error) bool
- func New(text string) error
- func Unwrap(err error) error
Examples ¶
Functions ¶
func As ¶
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.
As will panic if target is not a non-nil pointer to either a type that implements
error, or to any interface type. As returns false if err is nil.
Code:play
Output:Example¶
package main
import (
"errors"
"fmt"
"os"
)
func main() {
if _, err := os.Open("non-existing"); err != nil {
var pathError *os.PathError
if errors.As(err, &pathError) {
fmt.Println("Failed at path:", pathError.Path)
} else {
fmt.Println(err)
}
}
}
Failed at path: non-existing
func Is ¶
Is reports whether any error in err's chain matches target.
An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.
func New ¶
New returns an error that formats as the given text.
Code:play
Output: The fmt package's Errorf function lets us use the package's formatting
features to create descriptive error messages.
Code:play
Output:Example¶
package main
import (
"errors"
"fmt"
)
func main() {
err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
fmt.Print(err)
}
}
emit macho dwarf: elf header corrupted
Example (Errorf)¶
package main
import (
"fmt"
)
func main() {
const name, id = "bimmler", 17
err := fmt.Errorf("user %q (id %d) not found", name, id)
if err != nil {
fmt.Print(err)
}
}
user "bimmler" (id 17) not found
func Unwrap ¶
Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.
Source Files ¶
- Version
- v1.13.0-beta.1
- Published
- Jun 26, 2019
- Platform
- js/wasm
- Imports
- 1 packages
- Last checked
- 44 seconds ago –
Tools for package owners.