These steps cover the writing and running of your application:
- From your Terminal/console application, create a new directory called ~/projects/go-programming-cookbook/chapter4/basicerrors and navigate to this directory.
- Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter4/basicerrors
You should see a file called go.mod that contains the following:
module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter4/basicerrors
- Copy tests from ~/projects/go-programming-cookbook-original/chapter4/basicerrors, or use this as an exercise to write some of your own code!
- Create a file called basicerrors.go with the following content:
package basicerrors
import (
"errors"
"fmt"
)
// ErrorValue is a way to make a package level
// error to check against. I.e. if err == ErrorValue
var ErrorValue = errors.New("this is a typed error")
// TypedError is a way to make an error type
// you can do err.(type) == ErrorValue
type TypedError struct {
error
}
//BasicErrors demonstrates some ways to create errors
func BasicErrors() {
err := errors.New("this is a quick and easy way to create an error")
fmt.Println("errors.New: ", err)
err = fmt.Errorf("an error occurred: %s", "something")
fmt.Println("fmt.Errorf: ", err)
err = ErrorValue
fmt.Println("value error: ", err)
err = TypedError{errors.New("typed error")}
fmt.Println("typed error: ", err)
}
- Create a file called custom.go with the following content:
package basicerrors
import (
"fmt"
)
// CustomError is a struct that will implement
// the Error() interface
type CustomError struct {
Result string
}
func (c CustomError) Error() string {
return fmt.Sprintf("there was an error; %s was the result", c.Result)
}
// SomeFunc returns an error
func SomeFunc() error {
c := CustomError{Result: "this"}
return c
}
- Create a new directory named example and navigate to it.
- Create a main.go file with the following content:
package main
import (
"fmt"
"github.com/PacktPublishing/
Go-Programming-Cookbook-Second-Edition/
chapter4/basicerrors"
)
func main() {
basicerrors.BasicErrors()
err := basicerrors.SomeFunc()
fmt.Println("custom error: ", err)
}
- Run go run main.go.
- You may also run the following commands:
$ go build
$ ./example
You should now see the following output:
$ go run main.go
errors.New: this is a quick and easy way to create an error
fmt.Errorf: an error occurred: something
typed error: this is a typed error
custom error: there was an error; this was the result
- If you copied or wrote your own tests, then go up one directory and run go test. Ensure that all the tests pass.