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

The error type

Other Error functions:

  • Cause

  • Cause (Printf)

  • Errorf (Extended)

  • New

  • New (Printf)

  • WithMessage

  • WithStack

  • WithStack (Printf)

  • Wrap

  • Wrap (Extended)

  • Wrapf

  • package (StackTrace)

more examples

Last updated

Was this helpful?