0

I have several data to load, and If one of them fails, I have to log error and not continue to run the code.
Is this code OK? And how to do that?

func (worker *Worker) GetData() error {
  err := worker.LoadModelA()
  if err != nil && worker.LogError()  // LogError alway return true
    return err

  err = worker.LoadModelB()
  if err != nil && worker.LogError()  // LogError alway return true
    return err

  return err
}

2 Answers 2

1

With error in A (try it on The Go Playground), output:

LoadModelA
2009/11/10 23:00:00 LogError
2009/11/10 23:00:00 Error LoadModelB

With error in B (try it on The Go Playground), output:

LoadModelA
LoadModelB
2009/11/10 23:00:00 LogError
2009/11/10 23:00:00 Error LoadModelB

Without error (try it onThe Go Playground), output:

LoadModelA
LoadModelB
Done.
main Done.

Here is the code:

package main

import (
    "fmt"
    "log"
)

func (worker *Worker) GetData() error {
    if err := worker.LoadModelA(); err != nil {
        worker.LogError()
        return err
    }
    if err := worker.LoadModelB(); err != nil {
        worker.LogError()
        return err
    }
    fmt.Println("Done.")
    return nil
}

func main() {
    w := &Worker{}
    err := w.GetData()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("main Done.")
}

type Worker struct{}

func (w *Worker) LoadModelA() error {
    fmt.Println("LoadModelA")
    return nil
    //return fmt.Errorf("Error LoadModelB")
}
func (w *Worker) LoadModelB() error {
    fmt.Println("LoadModelB")
    return nil
    //return fmt.Errorf("Error LoadModelB")
}
func (w *Worker) LogError() error {
    log.Println("LogError")
    return nil
}
Sign up to request clarification or add additional context in comments.

4 Comments

I hope this helps. Is this what you are looking for?
I think your way is better than mine. Thanks Amd . I just get started golang. Do you know any forum or blog guid new guy like me to get better coding :)
Yup! Thanks a ton ;)
@Peter_175 A few good resources: reddit.com/r/golang, forum.golangbridge.org, and #go-nuts IRC channel (irc.lc/freenode/go-nuts)
0

With a small number of "several" you can simply have

func (worker *Worker) GetData() (err error) {
    if err = worker.LoadModelA(); err == nil {
        if err = worker.LoadModelB(); err == nil {
            return
        }
    }
    worker.LogError()
    return
}

On large numbers you can loop through the fields of struct

Comments

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.