Created
February 7, 2017 16:47
-
-
Save burdenless/a42c0ccb8b20ccbc1e6a8f1600b03ba1 to your computer and use it in GitHub Desktop.
Handle errors in goroutines with a single channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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