Golang正确的Error处理方式

2019-06-14  本文已影响0人  FredricZhu
package main

import (
    "fmt"
    "net/http"
)

type Result struct {
    Error    error
    Response *http.Response
}

func main() {
    checkStatus := func(done <-chan interface{},
        urls ...string) <-chan Result {
        results := make(chan Result)
        go func() {
            defer close(results)
            for _, url := range urls {
                resp, err := http.Get(url)
                result := Result{
                    Error:    err,
                    Response: resp,
                }

                select {
                case <-done:
                    return
                case results <- result:
                }
            }
        }()
        return results
    }

    done := make(chan interface{})
    defer close(done)
    urls := []string{"https://www.baidu.com", "https://badhosts"}
    for result := range checkStatus(done, urls...) {
        if result.Error != nil {
            fmt.Printf("Error: %v \n", result.Error)
            continue
        }
        fmt.Printf("Response: %v \n", result.Response.Status)
    }
}

程序输出如下,将Error返回给main goroutine进行处理。也就是返回给调用方进行处理。


image.png
上一篇下一篇

猜你喜欢

热点阅读