How to Create Custom Errors using New Function in Golang?
Last Updated :
15 Apr, 2020
Custom errors are those that can be defined by the user. For example, if one writes a function that is used to divide two numbers, which is to be used in multiple places, the user could create a custom error that can be set whenever division by zero is encountered, for it could prove to be fatal in the long run.
The easiest way to create custom errors in Golang is to use the New() function which is present in the errors module of Golang. 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
func New(text string) error {
return &errorString{text}
}
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 := -2.0
if side < 0.0 {
fmt.Println(errors.New( "Negative value entered!" ))
return
}
fmt.Printf( "Area= %f" , side*side)
}
|
Output:
Negative value entered!
This was so because we had entered the length of side as -2, 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 := -2.0
err, area := findAreaSquare(side)
if err != nil {
fmt.Printf( "%s" , err)
return
}
fmt.Printf( "Area= %f" , area)
}
|
Output:
Negative value entered!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...