func ThisFunctionIsNotGoingToFail_Probably(...) error {
// very secure code
}
It’s very unlikely that the previous function will fail. But It could fail in some specific situation (for example, during an extraterrestrial invasion). Is it correct to simply write:
ThisFunctionIsNotGoingToFail_Probably(…);
Or should I write?
if err := ThisFunctionIsNotGoingToFail_Probably; err != nil {
panic(err)
}
How should your program behave in case of an error? Can it continue to do what it does even after the funciton failed? If yes, you can ignore the error. But I would recommend to at least log it. So use the second form.
Ok, this language makes me think. And that’s good. Here’s my approach.
First case: The mentioned function belongs to a project. In that case, it shouldn’t return any error. Instead, the function should handle it’s own errors:
// This function belongs to a project
func ThisFunctionIsNotGoingToFail_Probably(…) {
// a very secure code (…probably)
if err != nil {
log.Fatal(error)
}
}
// … And then we can use it securely from other places of the project
ThisFunctionIsNotGoingToFail_Probably(…)
…
ThisFunctionIsNotGoingToFail_Probably(…)
Second case: The previous function belongs to an external library. In that case, the function should return an error and we should handle it:
// This function is declared in an external library
func ThisFunctionIsNotGoingToFail_Probably(…) error {
// very secure code
}
// … and we handle errors in our project or library
if err := ThisFunctionIsNotGoingToFail_Probably(…) {
panic(error) // or log.Fail(error), etc…
}
And that’s basically the rules I’m going to follow.
Sorry for my Spanglish
First of all, you shouldn’t call the panic function. It’s only used for really-exceptional cases. Normally, you just handle the error by logging or terminating the program gracefully etc.
In addition to that, you should always handle the errors, whether your function belongs to a local package or to an external package or not.
Regarding your question:
Some function like strconv.Atoi for example, usually returns 0 when an error happens. So, sometimes you may omit handling it. Or, fmt.Println for example also returns an error, but we usually don’t handle it.