Golang:无法在recover()中向通道发送错误。

huangapple go评论82阅读模式
英文:

Golang: Cannot send error to channel in recover()

问题

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

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()
}

我期望会打印出"err in range",但实际上没有打印出来。为什么呢?

英文:

I try to send an error in the channel on recovery
Why this error is not sent to the channel?

package main

import (
	&quot;fmt&quot;
	&quot;sync&quot;
	&quot;errors&quot;
)

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 &lt;- errors.New(&quot;recover err&quot;)
		 }
		 close(batchErrChan)
		 wg.Done()
   	   }()

	   panic(&quot;ddd&quot;)
    }(batchErrChan)

    go func() {
       for _ = range batchErrChan {
         fmt.Println(&quot;err in range&quot;)
       }
    }()
	
    wg.Wait()
}

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

I expect "err in range" to be printed, but it is not. Why?

答案1

得分: 3

你的程序在goroutine有机会打印消息之前就结束了。尝试等待它:

        ...
        done := make(chan struct{})
        go func() {
            for _ = range batchErrChan {
                fmt.Println("err in range")
            }
            close(done)
        }()

        wg.Wait()
        <-done
}

你可以将以上代码添加到你的程序中,以确保在等待goroutine完成之后再结束程序。

英文:

Your program ends before the goroutine gets a chance to print the message. Try waiting to it:

        ...
        done:=make(chan struct{})
        go func() {
         for _ = range batchErrChan {
            fmt.Println(&quot;err in range&quot;)
         }
         close(done)
       }()
	
       wg.Wait()
       &lt;-done
}

huangapple
  • 本文由 发表于 2021年10月25日 23:59:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/69711266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定