🚀 Get 25% off access to all my premium courses - use discount code FUNCMAIN at checkout - view the pricing page now!

Video:

Errors in Go

August 20, 2021

Course Instructor: Elliot Forbes

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now.

Now, if you are used to languages like Java, Python, or PHP, you may be used to the concept of throwing exceptions when parts of your code encounter errors they cannot handle.

Go is different to these languages as it does not feature exceptions at all. You can certainly use the panic keyword, however it’s recommended to avoid using this for most situations.

Instead of Panicking, Go developers pass errors as values. Typically, when you call a function it will more often than not return 2 or more values with the last value being an error.

When you call such a function, the best practice is then to check the error to see if it isn’t nil.

Defining Errors

Let’s start off by looking at how we can define errors in Go. Let’s say we have a function that takes in an integer and checks if it is a valid even number. If it’s not an even number then it will return an error:

package main

import "errors"

func IsEven(num int) error {
  if num % 2 != 0 {
    return errors.New("number is not even")
  }
  return nil
}

func main() {
  err := IsEven(24)
  if err != nil {
    fmt.Println("handle the error")
    fmt.Println(err)
  }

  err = IsEven(25)
  if err != nil {
    fmt.Println("handle the error")
    fmt.Println(err)
  }
}

Let’s try run this and see what happens:

$ go run main.go
handle the error
number is not even

Wrapping Errors

Imagine the situation where you are building a service. Your service might call another API in order to achieve some goal before returning a response.

Conclusion

Let’s recap what we’ve covered in this video. We’ve looked at how we can define custom errors in Go and how we can do more advanced things like wrapping the errors before passing them back to upstream callers.