Golang - Chapter 7

Errors

Returning Errors

By convention, the last return value is an error with also the type 'error'. If there are no errors to be returned, we can simply return nil in the error position.

package main

import (
	"fmt"
	"errors"
)

func main() {
    i, err := f()
    
    // we check if an error exists
    if err != nil {
        fmt.Println(err)	// not executed
        return
    }
    fmt.Println(i)	// prints 5
    
    j, err := g()
    if err != nil {
        fmt.Println(err) // prints "invalid"
        return
    }
    fmt.Println(j)	// not executed
}

func f() (int, error) {
    return 5, nil
} 

func g() (int, error) {
    return 0, errors.New("invalid")
} 

In the above example, f() returns no error, while g() returns an error with description as "invalid".

We have actually created a "custom" error using the errors.New() method. Similarly, you can pass any string to this method and return a custom error message.

comments powered by Disqus

Related