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.
errors package?errors is a package that contains methods for manipulating errors.
New method?The New method generates errors with merely a text message as their content.
New methodThe syntax for this method is New (Errorf).
New methodYou basically pass in the description of the error as a parameter.
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")}}
We imported the errors package, which we used to create errors.
We imported fmt package, which we used to print the error.
We use errors alongside the New() method, which allows you to create your error with a custom message.
Please run the code above to see the output.