Junior — Middle
Kas saaks jagada näidet, kuidas sa oled rakendanud vigade haldamist error.Group abil oma projektides?
sobes.tech AI
Vastus AI-lt
In the errors package of Go with the Group type (for example, from golang.org/x/sync/errgroup), it is easy to collect and handle multiple errors occurring in parallel goroutines.
Example of using errgroup.Group for executing tasks in parallel with error handling:
import (
"fmt"
"golang.org/x/sync/errgroup"
)
func processTasks() error {
var g errgroup.Group
tasks := []func() error{
func() error { /* task 1 */ return nil },
func() error { /* task 2 */ return fmt.Errorf("error in task 2") },
func() error { /* task 3 */ return nil },
}
for _, task := range tasks {
t := task
g.Go(func() error {
return t()
})
}
if err := g.Wait(); err != nil {
// Handle the first encountered error
return err
}
return nil
}
In my projects, I have used errgroup to start multiple independent operations in parallel and to collect errors in an organized manner, which simplifies the code and improves readability.