
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Handle Errors Within WaitGroups in Golang
There are chances that we might get some panic while running multiple goroutines. To deal with such a scenario, we can use a combination of channel and waitgroups to handle the error successfully and not to exit the process.
Let's suppose there's a function that when invoked returns a panic, which will automatically kill the execution of the program, as when panic gets called it internally calls os.Exit() function. We want to make sure that this panic doesn't close the program, and for that, we will create a channel that will store the error and then we can use that later to print the error with the help of the select statement.
The main idea behind the code shown below is −
To create two channels, one will hold an error, the other will denote the WaitGroup.
A goroutine, that is used to wait for the WaitGroup to finish, and also used to close the channel when that happens.
The select statement is used for listening to errors or the WaitGroup to complete.
Example
Consider the code shown below.
package main import ( "errors" "log" "sync" ) func main() { fatalErrorChannel := make(chan error) wgDone := make(chan bool) var wg sync.WaitGroup wg.Add(2) go func() { log.Println("First WaitGroup") wg.Done() }() go func() { log.Println("Second WaitGroup") err := returningError() if err != nil { fatalErrorChannel <- err } wg.Done() }() go func() { wg.Wait() close(wgDone) }() select { case <-wgDone: break case err := <-fatalErrorChannel: close(fatalErrorChannel) log.Fatal("Error encountered: ", err) } log.Println("Program worked!") } func returningError() error { return errors.New("Error on panic.com") }
Output
When we run this code, it will produce the following output −
2022/02/21 09:15:43 Second WaitGroup 2022/02/21 09:15:43 Error encountered: Error on panic.com exit status 1
It should be noted that the output may vary in your machine, but it is for sure that you will encounter the error message.