I've been reading this blog post but I'm still not convinced I know exactly what to do to get custom errors that I can return from my functions and handle outside of them.
This is what I'm currently doing:
func doSomething() int {
x := 0
// Do something with x.
...
if somethingBadHappened {
return -1
}
if somethingElseBadHappened {
return -2
}
return x
}
This is what I'd like to be doing:
func doSomething() int, ? {
...
if somethingBadHappened {
return ?, err
}
if somethingElseBadHappened {
return ?, err2
}
return x, nil
}
But I'm not exactly sure how, and what to replace those question marks with.
You don't really need to return an int if you don't want to. You can do something like:
func doSomething() error {
...
if somethingBadHappened {
return errors.New("something bad happened")
}
if somethingElseBadHappened {
return errors.New("something else bad happened")
}
return nil
}
or if you want to return ints
func doSomething() (int, error) {
...
if somethingBadHappened {
return -1, errors.New("something bad happened")
}
if somethingElseBadHappened {
return -2, errors.New("something else bad happened")
}
return x, nil
}
be sure to import "errors"
at the top.
If you want to test whether you got an error, you can do
x, err := doSomething()
if err != nil {
log.Println(err)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With