异步任务中的错误传递

并发编程下,如何将goroutine中发生的错误传递给其他程序,从而进行优雅的处理呢,
一种解决方案是,将异步任务中产生的错误写入通道中,在另一个程序中读取该通道,从而实现通信,二次处理错误信息

例子

package main

import (
	"fmt"
	"log"
	"net/http"
	"sync"
)

// 错误信息的封装
type Result struct {
	Error    error
	Response *http.Response
}

func main() {
	// 又不可达的链接,会触发错误
	urls := []string{"http://10.102.49.2/web_client/#/main", "http://10.102.204.36/console-acp/workspace/eop~region-k1~eop-uat8/deployment/detail/eop-dpl-cir-u6", "http://123.com"}
	for result := range checkStatus(urls) {
		if result.Error != nil {
			// 在此进行错误处理
			fmt.Printf("Error: %v\n", result.Error)
			continue
		}
		fmt.Printf("Response: %v\n", result.Response)
	}

}

// 将任务的处理结果放入通道中,并返回
func checkStatus(urls []string) <-chan Result {
	results := make(chan Result)
	go func() {
		defer close(results)
		var wg sync.WaitGroup
		for _, url := range urls {
			log.Println("visist: ", url)
			wg.Add(1)
			go func(url string) {
				defer wg.Done()
				resp, err := http.Get(url)
				// 将结果写入通道
				results <- Result{Error: err, Response: resp}
			}(url)
		}
		wg.Wait()
	}()
	return results
}