How to propagate errors in goroutines to main

I’m probably the victim of my own flawed thinking here, but…
The situation is the following: I am calling some goroutines from my main routine and everything works nice with waitgroups, error handling and all. But I need to let the main routine know if there has been certain types of errors in the goroutines and take action on that in the main routine. I can’t seem to crack that.
So, how do I get messages of errors occurring in a goroutine to propagate to the main routine? Something like:

funk main() {
...doing a lot here...
errGps := go gps.GetGpsData()
...then take care of the consequences...

func GetGpsData() error {
...doing something that goes wrong...
if errMessage != nil {
... take care of the local problem...
   return errMessage}

This obviously doesn’t work but how should it be done?

Two suggestions for getting started:

  1. Create a channel specifically for sending error values.


  1. Use an ErrGroup — this is like a WaitGroup but with error handling.

Create a channel of type error in the main function, pass it to the goroutines, send errors up this channel when they occur, handle them in the main function. Done.

Your goroutines should not return the error (or anything at all), they should use channels to send errors or results to the routines that handle them.


Thank you guys! You create a nice problem for me as I assume I can only mark one reply as the one solving the problem - and you posted practically simultaneously :slight_smile: Hope you understand that I value both of you equally.

Best /Brus


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.