Go Error Handling
Go provides a simple error handling mechanism through its built-in error interface.
The error type is an interface type, defined as follows:
type error interface {
Error() string
}
We can generate error messages in our code by implementing the error interface type.
Functions typically return error messages in their final return value. Using errors.New
can return an error message:
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, errors.New("math: square root of negative number")
}
// implementation
}
In the example below, we pass a negative number to Sqrt and receive a non-nil error object. Comparing this object to nil results in true, so fmt.Println
(fmt package calls the Error method when handling errors) is invoked to print the error. See the example code below:
result, err := Sqrt(-1)
if err != nil {
fmt.Println(err)
}
Example
package main
import (
"fmt"
)
// Define a DivideError struct
type DivideError struct {
dividee int
divider int
}
// Implement the `error` interface
func (de *DivideError) Error() string {
strFormat := `
Cannot proceed, the divider is zero.
dividee: %d
divider: 0
`
return fmt.Sprintf(strFormat, de.dividee)
}
// Define a function for integer division
func Divide(varDividee int, varDivider int) (result int, errorMsg string) {
if varDivider == 0 {
dData := DivideError{
dividee: varDividee,
divider: varDivider,
}
errorMsg = dData.Error()
return
} else {
return varDividee / varDivider, ""
}
}
func main() {
// Normal case
if result, errorMsg := Divide(100, 10); errorMsg == "" {
fmt.Println("100/10 = ", result)
}
// Error case when the divider is zero
if _, errorMsg := Divide(100, 0); errorMsg != "" {
fmt.Println("errorMsg is: ", errorMsg)
}
}
Executing the above program outputs:
100/10 = 10
errorMsg is:
Cannot proceed, the divider is zero.
dividee: 100
divider: 0