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 mainimport ("errors""fmt")func main() {numtest :=1sampleErr := errors.New("error occured")if(numtest == 2){fmt.Println(sampleErr)}else{fmt.Print("Correct")}}
Explanation
-
We imported the
errorspackage, which we used to create errors. -
We imported
fmtpackage, which we used to print the error. -
We use
errorsalongside theNew()method, which allows you to create your error with a custom message.
Output
Please run the code above to see the output.