How to do it...

These steps cover the writing and running of your application:

  1. From your Terminal/console application, create a new directory called ~/projects/go-programming-cookbook/chapter4/basicerrors and navigate to this directory.
  2. 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    
  1. Copy tests from ~/projects/go-programming-cookbook-original/chapter4/basicerrors, or use this as an exercise to write some of your own code!
  2. 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)

}
  1. 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
}
  1. Create a new directory named example and navigate to it.
  2. 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)
}
  1. Run go run main.go.
  2. 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
  1. If you copied or wrote your own tests, then go up one directory and run go test. Ensure that all the tests pass.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.181.52