1

I've the following function which iterate on list of response and if success print ok or error, at the end (after the function finished to execute) I need to return http 200 (if ok or 200 conditon is valid always) or http 500 if failure (even one failure) .I can use some flag (which I want to avoid) but is there a cleaner way to do it in Golang?

func getResults(results chan resultsList) {
    for res := range results {
        if res.Data != "ok" && res.Data != 200 {
            fmt.Println("error")
        } else {
            fmt.Printf("finish time %s \n", res.Name)
        }
    }
}
1
  • if the function should return failure even for a single failure, why do you want to keep processing the channel after the first failure ? To drain it or for other reasons ? Commented Oct 6, 2020 at 6:10

2 Answers 2

2

I prefer the "return early" style in these cases. Here is some example:

import (
   "fmt"
   "log"
)

func getResults(results chan resultsList) error {
   for res := range results {
      if res.Data != "ok" || res.Data != 200 {
         return fmt.Errorf("Data: %v", res.Data)
      }
      fmt.Println("finish time", res.Name)
   }
   return nil
}

func main() {
   e := getResults(something)
   if e != nil {
      log.Fatal(e)
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I'd say the way you wrote it is pretty clean already, to improve it you could use tagless switch statements, which would allow for overlapping conditions, meaning you could return detailed error messages for every error that may occour.

Other than that, you could maybe put a break statement into your if block, depending on wheather you want to know all errors or just if any error has occured.

2 Comments

ok, but how would you suggest to return the end result? if one iteration fails return 500 and if all success return 200...
Depends if you want to actually return those values/results. If you just want to print that there was an error, then you don't need to return anything, just print it. If you want to take action depending on which error happened then you could return a slice of unsigned integers, and iterate over that, or write the logic directly into the function you provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.