Home > database >  Golang: Cannot send error to channel in recover()
Golang: Cannot send error to channel in recover()

Time:10-26

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

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

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

CodePudding user response:

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("err in range")
         }
         close(done)
       }()
    
       wg.Wait()
       <-done
}
  • Related