Error Handling
Learn about errors in Go.
We'll cover the following...
Errors in Go
Errors are normal values within Go. We can deal with them in the same way we deal with other types, such as int, string, bool, and so on.
How we can define an error
There are three different ways we can define an error:
- By implementing the
error
interface - By calling the
errors.New()
function - By calling the
fmt.Errorf()
function
Let’s see the first two methods in action in the code snippet below:
Press + to interact
package mainimport ("errors""fmt")// 1. defining struct for errortype CustomErr struct {Code stringErrorMsg string}// 2. implement error interfacefunc (c *CustomErr) Error() string {return fmt.Sprintf("code: %q\nmessage: %q", c.Code, c.ErrorMsg)}func Divide(a, b int) (int, error) {if b == 0 {// 3. return our custom errorreturn 0, &CustomErr{Code: "INVALID", ErrorMsg: "cannot divide by 0"}}return a / b, nil}func main() {a, b := 3, 0_, err := Divide(a, b)if err != nil {// 4. run the Error() method on error returnedfmt.Println(err.Error())// 5. other method to create an errorerr = errors.New("sample error")fmt.Println(err.Error())return}}
In the example, the program checks for the error ...