M
M
Michael92020-09-15 11:53:23
go
Michael9, 2020-09-15 11:53:23

Am I handling errors from goroutines correctly?

Hey! I have a function in which I receive updates from the telegram bot and call the respond function in the goroutine to process the update. Errors that occur in respond I send to the error channel, and then I process errors in the select.

Is this error handling approach from goroutines correct, or are there better methods?

errChan := make(chan error)

  for {
    updates, err := b.getUpdates(offset)
    ....
    for _, upd := range updates {
                ....
      		       go respond(upd, errChan)

      select {
      case err := <-errChan:
        log.Println("Error from channel:", err)
      default:
        continue
      }
    }
  }


In the respond method:

...
        message, err := s.GetMessage(upd.Message.Text)
  if err != nil {
    errChan <- err
  }
.....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Supme, 2020-09-26
@Supme

Incorrect.
And why not write to the log in the goroutine itself?
Or you need a separate eternal goroutine that handles errors.
In your case, it makes no sense to run a goroutine, your cycle on the channel is blocked, and if the channel is with a buffer, then it’s not at all clear what will happen :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question