Error

package errors and fmt.Errorf. Below implementation is by errors package.

package main

import (
	"fmt"
	"errors"
)

// error are last return value
func f1(arg int) (int, error){
	if arg == 42 {
	// error.New constructs new error value with given message
	return 3, errors.New("not allowed")
	}

	return arg*2, nil
}

// customize error struct
type argError struct{
	arg int
	msg string
}

func (e *argError) Error() string{
	return fmt.Sprintf("%d - %s", e.arg, e.msg)
}

func f2(arg int) (int, error){
	if arg == 42{
		return -1, &argError{arg, " wrong"}
	}
	return 123,nil
}

func main(){

// range returns index and value
for _, i :=  range []int{7,42}{
	if r,e := f1(i); e != nil {
		fmt.Println(e)
	}else {
		fmt.Println(r)

}

}
	for _, i := range []int{7, 42} {
        if r, e := f2(i); e != nil {
            fmt.Println("f2 failed:", e)
        } else {
            fmt.Println("f2 worked:", r)
        }
    }
}

Non nil Error while opening a file

f, err := os.Open("filename.ext")
if err != nil {
    log.Fatal(err)
}
// do something with the open *File f

The error type

type error interface {
    Error() string
}

Other Error functions:

  • Cause

  • Cause (Printf)

  • Errorf (Extended)

  • New

  • New (Printf)

  • WithMessage

  • WithStack

  • WithStack (Printf)

  • Wrap

  • Wrap (Extended)

  • Wrapf

  • package (StackTrace)

more examples

package main

import (  
    "fmt"
    "os"
)

func main() {  
    f, err := os.Open("test.txt")
    if err != nil {
        if pErr, ok := err.(*os.PathError); ok {
            fmt.Println("Failed to open file at path", pErr.Path)
            return
        }
        fmt.Println("Generic error", err)
        return
    }
    fmt.Println(f.Name(), "opened successfully")
}

Last updated

Was this helpful?