Handling Errors in Goroutines

If your application relies on many goroutines it can be easy to forget to properly handle errors:

func Do() {
    go func() {
        a := make([]int, 1)
        a[1] = 0 /* Index out of bounds! */
    }()
}

If your goroutine doesn’t require returning a result at a later time, try using a defer/recover to catch errors at runtime:

go func() {
    defer func() {
        if err := recover(); err != nil {
            log.Printf("An error occurred: %s", err)
        }
    }()

    a := make([]int, 1)
    a[1] = 0
}()

Otherwise, define a struct that lets you return a result or error :

type Result struct {
    Value int
    Err   error
}

func Do() {
    c := make(chan Result)

    go func(r chan Result) {
        result, err := doExpensiveStuff()
        r <- Result{result, err}
    }(c)

    r := <-c
    if r.Err != nil {
        log.Fatal(r.Err)
    }
}