Golang:无法在恢复()中向通道发送错误

我尝试在恢复时在通道中发送错误 为什么这个错误没有发送到通道?


package main


import (

    "fmt"

    "sync"

    "errors"

)


func main() {

    var wg sync.WaitGroup

    wg.Add(1)

    batchErrChan := make(chan error)

    

    go func(errchan chan error) {

       defer func() {

         if r := recover(); r != nil {

            errchan <- errors.New("recover err")

         }

         close(batchErrChan)

         wg.Done()

       }()


       panic("ddd")

    }(batchErrChan)


    go func() {

       for _ = range batchErrChan {

         fmt.Println("err in range")

       }

    }()

    

    wg.Wait()

}


https://play.golang.org/p/0ytunuYDWZU


我希望打印“范围内的错误”,但事实并非如此。为什么?


慕尼黑5688855
浏览 102回答 1
1回答

摇曳的蔷薇

你的程序在 goroutine 有机会打印消息之前结束。尝试等待它:&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; done:=make(chan struct{})&nbsp; &nbsp; &nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for _ = range batchErrChan {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("err in range")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;close(done)&nbsp; &nbsp; &nbsp; &nbsp;}()&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;wg.Wait()&nbsp; &nbsp; &nbsp; &nbsp;<-done}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go