Error Handling

Learn about errors in Go.

Errors in Go

Errors are normal values within Go. We can deal with them in the same way we deal with other types, such as int, string, bool, and so on.

How we can define an error

There are three different ways we can define an error:

  • By implementing the error interface
  • By calling the errors.New() function
  • By calling the fmt.Errorf() function

Let’s see the first two methods in action in the code snippet below:

Press + to interact
package main
import (
"errors"
"fmt"
)
// 1. defining struct for error
type CustomErr struct {
Code string
ErrorMsg string
}
// 2. implement error interface
func (c *CustomErr) Error() string {
return fmt.Sprintf("code: %q\nmessage: %q", c.Code, c.ErrorMsg)
}
func Divide(a, b int) (int, error) {
if b == 0 {
// 3. return our custom error
return 0, &CustomErr{Code: "INVALID", ErrorMsg: "cannot divide by 0"}
}
return a / b, nil
}
func main() {
a, b := 3, 0
_, err := Divide(a, b)
if err != nil {
// 4. run the Error() method on error returned
fmt.Println(err.Error())
// 5. other method to create an error
err = errors.New("sample error")
fmt.Println(err.Error())
return
}
}

In the example, the program checks for the error ...