How to Handle Errors in Goroutines

Handle goroutine errors by sending results via channels or using defer with recover to catch panics.

Handle errors in goroutines by checking the returned error value immediately after the goroutine completes or by using a channel to send errors back to the main goroutine.

func worker(id int, results chan<- error) {
    defer func() {
        if r := recover(); r != nil {
            results <- fmt.Errorf("goroutine %d panicked: %v", id, r)
        }
    }()
    // Do work that might panic or return an error
    results <- nil
}

func main() {
    results := make(chan error, 1)
    go worker(1, results)
    if err := <-results; err != nil {
        log.Fatal(err)
    }
}