Should we always manage the function errors?

Let’s say that we have a “very secure” function:

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)
}

Thanks.

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.

1 Like

Ok, this language makes me think. And that’s good. Here’s my approach.

  1. 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(…)

  2. 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 :slight_smile:

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.

4 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.