How to create an error in Golang

Overview

Creating a custom error in your codes can be very useful and give you a better description of that error. So, in this shot, we will learn how to create custom errors using the errors package.

What is the errors package?

errors is a package that contains methods for manipulating errors.

What is the New method?

The New method generates errors with merely a text message as their content.

Syntax for the New method

The syntax for this method is New (Errorf).

Parameter for the New method

You basically pass in the description of the error as a parameter.

Example

For test purposes, to create a scenario we use an if statement to check a number, and then we create our error.

package main
import (
"errors"
"fmt"
)
func main() {
numtest :=1
sampleErr := errors.New("error occured")
if(numtest == 2){
fmt.Println(sampleErr)
}else{
fmt.Print("Correct")
}
}

Explanation

  1. We imported the errors package, which we used to create errors.

  2. We imported fmt package, which we used to print the error.

  3. We use errors alongside the New() method, which allows you to create your error with a custom message.

Output

Please run the code above to see the output.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources