Skip to content

Instantly share code, notes, and snippets.

@burdenless
Created February 7, 2017 16:47
Show Gist options
  • Save burdenless/a42c0ccb8b20ccbc1e6a8f1600b03ba1 to your computer and use it in GitHub Desktop.
Save burdenless/a42c0ccb8b20ccbc1e6a8f1600b03ba1 to your computer and use it in GitHub Desktop.
Handle errors in goroutines with a single channel
package main
import "fmt"
import "time"
// Goroutines Error Handling
// Example with same channel for Return and Error
type ResultError struct {
res Result
err error
}
type Result struct {
ErrorName string
NumberOfOccurances int64
}
func runFunc(outputChannel chan ResultError, errorId string) {
errors := map[string]Result {
"1001": {"a is undefined", 245},
"2001": {"Cannot read property 'data' of undefined", 10352},
}
time.Sleep(time.Second)
if r, ok := errors[errorId]; ok {
outputChannel <- ResultError{res: r, err: nil}
} else {
outputChannel <- ResultError{res: Result{}, err: fmt.Errorf("getErrorName: %s errorId not found", errorId)}
}
}
func getError(errorId string) (r ResultError) {
outputChannel := make (chan ResultError)
go runFunc(outputChannel, errorId)
return <- outputChannel
}
func main() {
fmt.Println("Using separate channels for error and result")
errorIds := []string{
"1001",
"2001",
"3001",
}
for _, e := range errorIds {
r := getError(e)
if r.err != nil {
fmt.Printf("Failed: %s\n", r.err.Error())
continue
}
fmt.Printf("Name: \"%s\" has occurred \"%d\" times\n", r.res.ErrorName, r.res.NumberOfOccurances)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment