Custom Errors in Go


Custom Errors in Go

In this tutorial, we will discuss how to create our own custom errors in the Go language, which we can use in functions and packages we create in the Go language.

Custom errors are those that can be defined by the user. In the custom error, we will be able to send errors according to our way or error, which is more understandable to the end-users.

Custom Errors in Go

Go language provides two methods to create errors in the standard library errors.New and fmt.Errorf.

Using the New function

The simplest way to create a custom error is to use the New function of the errors package. Before actually moving on to creating our error, let’s look at how it is implemented in the errors package.

// Package errors implements functions to manipulate errors.
package errors

// New returns an error that formats as the given text.
func New(text string) error {
    return &errorString{text}
}

// errorString is a trivial implementation of error.
type errorString struct {
    s string
}

func (e *errorString) Error() string {
    return e.s
}

So, basically, what the New() function does is create an error with a custom message that the programmer can write.

For example, let’s say we want an error to be displayed whenever a negative value is given as input for the program that outputs the area of a square, given its side.

package main

import (
	"errors"
	"fmt"
)

func main() {
	side := -3.0
	if side < 0.0 {
		fmt.Println(errors.New("Negative value entered!"))
		return
	}
	fmt.Printf("Area= %f", side*side)
}

Output

Negative value entered!

Run in playground

This was so because we had entered the length of the side as -3, which cannot be possible, and hence the error was thrown.

Now let’s try out a similar program but this time let’s put the error generation in a separate function.

package main

import (
    "errors"
    "fmt"
)

func findAreaSquare(side float64) (error, float64) {
    if side < 0.0 {
        return errors.New("Negative value entered!"), 0
    }
    return nil, side * side
}

func main() {
    side := -3.0
    err, area := findAreaSquare(side)
    if err != nil {
        fmt.Printf("%s", err)
        return
    }
    fmt.Printf("Area= %f", area)
}

Output

Negative value entered!

Run in playground

Using fmt.Errorf

This function formats the error according to a format specifier and returns a string as the value that satisfies the error.

package main

import (
    "fmt"
)

func main() {
    sampleErr := fmt.Errorf("Error is: %s", "Database connection issue")
    fmt.Println(sampleErr)
}

Output

Error is: database connection issue

Run in playground

Ignoring errors

We can use Underscore (‘_’) operator to ignore the error returned from a function call. Before we see a program, it’s important to note that errors should never be ignored. It is not a recommended way. Let’s see a program

package main

import (
    "fmt"
    "os"
)

func main() {
    file, _ := os.Open("non-existing.txt")
    fmt.Println(file)
}

Output

{nil}

We used the underscore operator to ignore the error in the above program while opening a non-existing file. That is why the file instance returned by the function is nil. Therefore it is better to check for an error before using any other argument returned by the function as that can be nil and would result in unwanted issues, and sometimes it might also result in a panic.

Custom Errors in Go
Scroll to top