Skip to content

Instantly share code, notes, and snippets.

@stasyanko
Forked from burdenless/goroutine_err_handling.go
Created November 16, 2017 10:25
Show Gist options
  • Select an option

  • Save stasyanko/e3e14d372b0f2a4025c8916dcf38220f to your computer and use it in GitHub Desktop.

Select an option

Save stasyanko/e3e14d372b0f2a4025c8916dcf38220f to your computer and use it in GitHub Desktop.

Revisions

  1. Bob Argenbright created this gist Feb 7, 2017.
    54 changes: 54 additions & 0 deletions goroutine_err_handling.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    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)
    }
    }