panic and recover

A panic cuts off the normal flow. It does not replace input checks, and you do not catch everything in every function.

panic stops the function and walks up the stack until it meets recover or kills the process. recover works only inside a deferred function:

defer func() {
    if rec := recover(); rec != nil {
        // процесс ещё жив, но инвариант уже под вопросом
    }
}()

recover outside defer always returns nil. It does not "catch exceptions in this block".

A panic is appropriate when you cannot continue, because this is a bug: an invariant was broken that the caller could not fix with their input. regexp.MustCompile panics on a crooked pattern that the programmer wrote into the code as a constant. You do not call MustCompile on a pattern from the user: that is an ordinary regular-expression compile error.

An HTTP server catches a panic at the request boundary, so one fallen handler does not take down the whole process, writes the stack, and answers 500. This is a safety net, not a way to return a validation error. Inside a library recover is almost always harmful: it hides a bug and leaves the program in an unknown state.

Do not confuse a panic with os.Exit. Exit does not run defer. A panic runs them while the stack unwinds. For an emergency exit from main, returning an error and a log plus a non-zero code is usually enough, without a panic.

If you are in doubt, return error. A panic is easy to add later and hard to clean out of an API: callers cannot handle it as a value without putting recover on every call.

Practice

  1. When to panic

    The user sent an empty email in JSON. What should the handler do?

    • panic("empty email")
    • Return an error and a response about a bad request
    • os.Exit(1)
    • recover immediately on the same line
  2. Where recover works

    Where can recover catch a panic?

    • On any following line after panic
    • Inside defer, while the panic unwinds the stack
    • In another goroutine, if you are quick
    • Inside init of any package
  3. What Must is for

    Why is regexp.MustCompile acceptable for a pattern written in the code as a constant, and bad for a pattern from a request?

    • The compiler itself checks a constant with a regular expression
    • A broken constant is a bug in the program, and user input must be returned as an error
    • MustCompile is faster than Compile
    • For a request MustCompile is actually preferable, because it is shorter