Handling Error in Go pipeline — A layman approach
In my previous articles, I have described how a Go pipeline works, how to use context, how to deal with multiple goroutines, etc. Now comes one important aspect that I have postponed to mention. It's error handling in goroutines. In this article, I will try to explain a naive approach to error handling.
A Brief Overview
Below is the most basic pipeline I can think about at this moment.
The pipeline consists of 2 stages. Stage 1 & Stage 2.
The worker (single worker for simplicity)in Stage 1 writes to a channel called data.
The worker (single worker for simplicity) in Stage 2 reads data from the same channel i.e data.
Now, let's assume that in Stage 1 there happened some error. How shall we propagate this error to Stage 2?
Probably below is a naive approach for the situation but it works quite fine as expected.
We have introduced a channel called error.
Any error that occurs in Stage 1 is written to the channel error.
In Stage 2, apart from reading data from the data channel, our worker will also poll (read) on the error channel.
Necessary actions can be taken in Stage 2 based on the errors received in the error channel.
Seems quite a simple approach!
Show me the code!!!
So, below is the simplest possible code for a layman I could come up with.
What's going on in the code?
In the first stage i.e b1, we have a single worker that is sending some integer to the data channel.
Also, if the generated random value equals to the number being sent, it generates an error and sends it to the error channel.
In the second stage i.e b2, we are simply reading the values sent to data as well as error channel.
Lastly, we are exiting the infinite for loop in stage b2 based on a condition. I have explained how to use this condition in this article.
That's it. I believe it can help any Go layman to get an idea of how to handle errors in a Go pipeline.
Happy Go learning!