Error is by far the most used interface in Go. lets have a look at it:
type error interface {
Error() string
}
//The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
So any type that implements the Error method is by default an error type. Some Examples:
package main
import "fmt"
type MyError string
func (me MyError) Error() string{
return string(me) //cast it back to string
}
type MyOtherError struct{
Code int
Message string
}
func (me MyOtherError) Error() string{
return fmt.Sprintf("error occurred: %s with code %d ",me.Message,me.Code)
}
func MyBadFunc()error{
return MyError("this is an error ") //cast it to a MyError
}
func MyOtherBadFunc()error{
return MyOtherError{Message:"MyOtherBadFunc failed ", Code:500}
}
func main(){
fmt.Println(MyBadFunc())
fmt.Println(MyOtherBadFunc())
}
In Go errors are values and are meant to be checked. They are not exceptions. The idiom in Go is very similar to node.js This is likely the most common code snippet in Go programs
if err != nil {
return err
}
This is likely the most commons snippet of code in node programs
if (err){
return cb(err);
}
Go tries to ensure you check your errors and you should always check your errors. Error states are very normal in running programs, they are part of your program not something that should just disappear.
One note on errors. As the are values you do not naturally get a stacktrace. I think Go could have done a better job here. However there are solutions. One of the go contributors wrote a compatible errors package github.com/pkg/errors I recommend using this package once you become a little more advanced.
go get github.com/pkg/errors
package main
import (
"fmt"
"github.com/pkg/errors"
)
func main() {
err := errors.New("my error with stack")
fmt.Printf("%+v", err) //the +v indicates to print the trace
}
A little light reading from the Go team on errors error are values