W3Basic Logo

Go Errors

When you are writing a program, a lot of things can go wrong. For example, you may try to open a file that does not exist, or to divide a number by a user input that happens to be zero. In these cases, you want to stop the program and display an error message to the user.

What is an error?

In Go, an error is an object that implements the error interface:

type error interface {
	Error() string

This interface has only one method, Error(), which returns a string.

Creating an error

You can create an error that is suitable for your program by implementing the error interface:

type MyError struct {
	Message string
	Time    time.Time

func (e MyError) Error() string {
	return fmt.Sprintf("ERROR: %s (%s)", e.Message, e.Time)

but if you only need to return a simple error, you can use the errors.New() function:

err := errors.New("ERROR: something went wrong")

or the fmt.Errorf() function:

err := fmt.Errorf("ERROR: %d is not a valid number", 42)

when you need to format the error message.

Defining a function that might return an error

When you define a function that might return an error, a common pratice is to return the result as the first value and the error as the second value:

func Divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("ERROR: cannot divide by zero")
	return a / b, nil

Note: It is also the way the standard library works. For example, the os.Open() function returns a pointer to a File structure and an error (that is nil if everything went well).

To handle the error, you then have this very common pattern:

result, err := Divide(10, 0)
if err != nil {
	// handle the error
// do something with the result

© 2023 W3Basic. All rights reserved.

Follow Us: