61

Go provides two ways of handling errors, but I'm not sure which one to use.

Assuming I'm implementing a classic ForEach function which accepts a slice or a map as an argument. To check whether an iterable is passed in, I could do:

func ForEach(iterable interface{}, f interface{}) {
    if isNotIterable(iterable) {
        panic("Should pass in a slice or map!")
    }
}

or

func ForEach(iterable interface{}, f interface{}) error {
    if isNotIterable(iterable) {
        return fmt.Errorf("Should pass in a slice or map!")
    }
}

I saw some discussions saying panic() should be avoided, but people also say that if program cannot recover from error, you should panic().

Which one should I use? And what's the main principle for picking the right one?

7

9 Answers 9

76

You should assume that a panic will be immediately fatal, for the entire program, or at the very least for the current goroutine. Ask yourself "when this happens, should the application immediately crash?" If yes, use a panic; otherwise, use an error.

8
  • 2
    Agreed. But how do I determine if the program can continue? For me, it seems that if some integer is accidentally passed in, there's no way for the program to continue running.
    – laike9m
    Jun 13, 2017 at 4:55
  • 3
    That may be the case. Perhapse "can continue" is a little vague - what it really means is, if the error occurred, is there any way your program could handle the error? Generally speaking, in go, if you're not sure, return an error. Panics should be pretty rare.
    – Adrian
    Jun 13, 2017 at 13:07
  • 5
    This reply is not an answer: it is a question (Ask yourself...).
    – dolmen
    Jul 19, 2018 at 13:59
  • 6
    Read it in its entirety. It encourages the reader to ask themselves a question, in order to offer logic based on the answer to make a decision for themselves.
    – Adrian
    Jul 19, 2018 at 14:01
  • 3
    At the same time, a post from the official blog suggests a different approach. They give the json library as an example, which uses panic internally and converts it to an error in the public API.
    – cubuspl42
    May 6, 2019 at 14:19
18

Use panic.

Because your use case is to catch a bad use of your API. This should never happen at runtime if the program is calling your API properly.

In fact, any program calling your API with correct arguments will behave in the same way if the test is removed. The test is there only to fail early with an error message helpful to the programmer that did the mistake. Ideally, the panic might be reached once during development when running the testsuite and the programmer would fix the call even before committing the bad code, and that incorrect use would never reach production.

See also this reponse to question Is function parameter validation using errors a good pattern in Go?.

5
  • 3
    Go's own blog states "The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values" so you should use error instead of panic. Also, your logic for using panic is somewhat flawed; should never happen if called correctly is like saying websites should stop sending a 404 error and start crashing the browser because no 404 should ever be issued if people type the URL correctly. If anything APIs and libraries need to be more tolerant of errors in use.
    – dasper
    Mar 9, 2022 at 21:04
  • 1
    @dasper Do you check for nil values every time your API takes a pointer/slice/map (even checking method receiver) to report an error? Or do you leave that check to the runtime?
    – dolmen
    Jun 1, 2022 at 16:52
  • 2
    I do not think pointers are a concern because you should not be allowing API requests that can explicitly declare a point in memory on the server. Regardless, you I have request/response contracts that need to be met otherwise it is an invalid request. This should be taken care of on your unmarshal/parse function. Error here would respond with invalid request; no reason to panic. If your allows for nil then it is not a reason to panic nor throw an error.
    – dasper
    Aug 30, 2022 at 18:24
  • @dasper I'm trying to understand the best way to handle errors in Go. If they only public interface of my code is a Web API why cannot I use panic internally and recover in a middleware function and then return an HTTP error to the user? Is not that the same as the convention you mention above "that even when a package uses panic internally, it's external API still presents explicit error return values". My error values are the 4xx/5xx HTTP status codes, the rest of code is internal to my service. Sep 1 at 21:57
  • @JuanHernandez Well, be honest with yourself. Are you using a panic because the something went wrong that you do not know how to return out of your code or are you using it as a quick GOTO to get to the middleware to handle the error? If it is the former then you can use a panic but if it is the latter then you are not properly handling the error. I have a much longer answer down below: stackoverflow.com/a/71304437/1050401
    – dasper
    Sep 2 at 23:21
6

I like the way it's done in some libraries where on top of a regular method DoSomething, its "panicky" version is added with MustDoSomething. I'm relatively new to go, but I've already seen it in several places, notably sqlx.
In general, if you want to expose your code to someone else, you should either have Must- and a regular version of the method, or your methods/functions should give the client a chance to recover the way they want and so error should be available to them in a go-idiomatic way.
Having said that, I agree that if your API/library is used inappropriately, it's Ok to panic as well. As a matter of fact, I've also seen methods like MustGetenv() that will panic if a critical env.var is missing. Fail-fast mechanism basically.

3

If some mandatory requirement is not provided or not there while starting the service (eg. database connection, some service configuration which is required) then you should use panic.

There should be return error for any user response or server side error.

2

Ask yourself these questions:

  • Do you expect the exceptional situation to occur, regardless how well would you code your app? Do you think it should be useful to make the user aware of such condition as part of the normal usage of your app? Handle it as an error, because it concerns the application as working normally.
  • Should that exceptional situation NOT occur if you code appropriately (and somewhat defensively)? (example: dividing by zero, or accessing an array element out of bounds) Is your app totally clueless under that error? Panic.
  • Do you have your API and want to ensure users use it appropriately? Panic. Your API will seldom recover if used incorrectly.
1

Use error whenever possible

Only use panic when your code could end up in a bad state that would be prone to crashing; something truly unexpected. The example above with ForEach() is an exported func that accepts an interface so it should expect someone will improperly call it. And if it is improperly called, you know why you cannot continue and you know how to handle that error. isNotIterable is literally binary and easy to control.

But error is not like a try/catch

Even if you try to justify panic/recover by looking at throw/catch from other languages, you still use errors. We know you are trying the function because you are calling it, we know there was an error because err != nil, and just like checking the type of exception thrown you can check the type of error returned with errors.Is(err, ErrNotIterable)

So should you use panic for errors in concurrency?

The answer is still most likely no. Errors are still the preferred way in Go and you can use a wait group to shut down the goroutines:

    ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
    // automatically cancel in 5 min
    defer cancel()
    errGroup, ctx := errgroup.WithContext(ctx)
    errGroup.Go(func() error {
        // do crazy stuff; you can still check for errors
        if ... {
            return fmt.Errorf("critical error, stopping all goroutines now")
        }
        // code completed without issues
        return nil
    })
    err = errGroup.Wait()

Even using the structure of the original example, you still have better control with errors than panics:

func ForEach(iterable interface{}, f interface{}) error {
    if isNotIterable(iterable) {
        return fmt.Errorf("expected something iterable but got %v", reflect.ValueOf(iterable).String())
    } 
    
    switch v.Kind() {
    case reflect.Map:
        ...
    case reflect.Array, reflect.Slice: 
        ...
    default:
        return fmt.Errorf("isNotIterable is false but I do not know how to iterate through %v", reflect.ValueOf(iterable).String())
}

But error feels very verbose

Yes, that is the point. When an error is returned, it is at that point to do something about it. You are giving the calling code options rather than making the decision to start shutting down and killing the application unless you recover(). If you are just returning the same error all the way up the call stack then error will seem inferior to panic, but this is due to not addressing issues when they happen.

So when to use panic?

When your code is on a collision course to crash and you cannot assume your way out of it. Another is when the code assumes something that is no longer true and having to check the integrity in every function from here on out would be tedious (and might impact performance). Still, you would use panic() only to get out of the layers of uncertainty... then still handle errors:

func ForEach(iterable interface{}, f interface{}) error {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("cannot iterate due to unexpected runtime error %v", r)
            return
        }
    }()
    ...
    // perhaps a broken pipe in a global var
    // or an included module threw a panic at you!
}

But if you are still not convinced... Here is the Go FAQ

We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code. It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional.

Go takes a different approach. For plain error handling, Go's multi-value returns make it easy to report an error without overloading the return value. A canonical error type, coupled with Go's other features, makes error handling pleasant but quite different from that in other languages.

0

A panic typically means something went unexpectedly wrong. Mostly used to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully. So in this case just return the error, you don't want your program to panic.

1
  • 2
    Define "normal operation". Because that's the point of the question: "is the check isNotIterable about normal operation?"
    – dolmen
    Jul 19, 2018 at 12:56
0

I think none of the previous answers are correct:

Putting it more formally, our "Turing Machine" is broken and we need to come back to an "stable state" or "reset state". More info at https://en.wikipedia.org/wiki/Reset_(computing)

For example in web (micro)services that means returning a 40X error (panic caused by input from user) or 50X error (panic caused by something else - hardware, network, assert error, ...)

  • If we know what to do with the "error", then we do not have an error in first place, but an uncomfortable return value. This is a normal execution condition and probably not an error. Normally this correspond to the happy vs non-happy path modeling.

In a summary, the err return value is mostly a wrong idea, even if the GO community has adopted it as a religion. Using error return values is just a patchy way to speed up program execution since it require fewer CPU instructions to be implemented, but most of the time, except for low-level services, it is useless and promote dirty code. (note that GO was designed to implement those low-level services as an "easy-C", but it was adopted for high-level (Level 7) application programs when an error must fail fast to avoid continuing with undefined states that can potentially cause money being lost of fatal casualties. In case of doubt, default to panic.

Update 2023-03: (Add Erlang reference) There are not opinionated or idiomatic ways to handler errors. There are correct ways and incorrect ways to handle errors. The correct way is the Erlang way (language designed to support ~100% of uptimes). C&P from intro

  • Crash early:
    • Let some other process do the error recovery
    • Do not program defensively
    • If you cannot handle the error, don’t try to recover

Update 2023-05: (Add Helm reference). The lovely designed Helm, while being Go based, duplicates the functionality of each defined function. By default, functions do panic, and when explicetely prefixed with must... they return an error. REF. Note that Helm is used to configure HA Kubernetes clusters.

Update 2023-09: C&P from: https://go.dev/doc/go1.14 "Runtime This release improves the performance of most uses of defer to incur almost zero overhead compared to calling the deferred function directly. As a result, defer can now be used in performance-critical code without overhead concerns." I guess that lack of performance is what made people be biased toward using a patching "return error" pattern. As the document explains, this is not true starting with go 1.14 (available for production since 2020/02).

3
  • 1
    I think your answer is deeply flawed and harmful advice. Go allows to fail fast by returning an error as its own value so at any moment you can return with a failure message. The error also allows you to reset to a stable state by inspecting the type of error you receive; even easier than an panic. Where you would use a panic is when you CANNOT recover the flow of control yourself as panic will crash the program if not recovered. If you are recovering immediately up the call stack with no other goroutines operating and a knowledge of why there is an error then you are doing it wrong.
    – dasper
    Mar 1, 2022 at 1:50
  • @dasper: if you can recorver inmediately up the call then there is no error. You have an standard set of possible values and some of them represent some 'psicologically negative' non-happy values. But a Touring machine can just return a defined value, timeout or fail with undefined behaviour, never with an error. If the error is contemplated it's just part of the well defined set of return values.
    – earizon
    Mar 1, 2022 at 19:13
  • 1
    Disagreeing with Go idioms is reasonable, but doesn't change the fact that they're Go idioms, and StackOverflow isn't the place to debate them. In Go, the accepted practice is to expose errors. "the err return value is mostly a wrong idea, even if the GO community has adopted it as a religion" flies in the face of the entire corpus of Go code, and is going to set up anyone following it for failure as a Go developer unless they work exclusively on solo projects.
    – Adrian
    Mar 1, 2022 at 20:27
-1

Don't use panic for normal error handling. Use error and multiple return values. See https://golang.org/doc/effective_go.html#errors.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.