Custom Errors in Go


Custom Errors in Go

In this tutorial, we are going to discuss about how to create our own custom errors which we can use in functions and packages we create in 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.

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 own error, let’s have a 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 can be written by the programmer.

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 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 value that satisfies 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

Custom Errors in Go


Scroll to top