Mastering Go Error Handling: Panic, Recover, and Best Practices

This article explains Go's error handling conventions, the built‑in error interface, how to use panic and recover for runtime exceptions, and presents practical patterns—including closure‑based handling and custom package guidelines—to write robust backend code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Go Error Handling: Panic, Recover, and Best Practices

Error

Return an error object as the sole or last return value of a function; if the returned value is nil, no error occurred, and the caller must always check the received error.

Error Handling

Handle errors and return error information to the user where the function fails; using panic and recover is reserved for true exceptional situations. Library functions usually must return some error indication to the caller.

To prevent a function (or the whole program) from being aborted when an error occurs, the caller must check the error after invoking the function.

if value, err := pack1.Func1(param1); err != nil {
    fmt.Printf("Error %s in pack1.Func1 with parameter %v", err.Error(), param1)
    // return // or: return err
}
// Process(value)

Runtime Exceptions and panic

When runtime errors such as array index out‑of‑bounds or failed type assertions occur, Go triggers a runtime panic, throwing a runtime.Error value. The panic function can be called directly for unrecoverable conditions; it prints the provided value and aborts the program.

package main
import "fmt"
func main() {
    fmt.Println("Starting the program")
    panic("A severe error occurred: stopping the program!")
    fmt.Println("Ending the program")
}

Output example:

Starting the program
panic: A severe error occurred: stopping the program!
...

Recover from panic

The built‑in recover function can be used inside a defer ‑ed function to regain control after a panic. If the program is not panicking, recover returns nil.

func protect(g func()) {
    defer func() {
        log.Println("done")
        if err := recover(); err != nil {
            log.Printf("runtime panic: %v", err)
        }
    }()
    log.Println("start")
    g() // may cause runtime panic
}

Custom package error handling and panicking

Best practices for custom packages:

Always recover from panics inside the package; do not let panics escape the package boundary.

Return error values to callers instead of panicking.

Within deep, non‑exported functions, using panic to signal an error scenario can be useful, provided it is recovered and translated to an error for the caller.

// parse.go
package parse
import (
    "fmt"
    "strings"
    "strconv"
)

type ParseError struct {
    Index int    // index of the word in the space‑separated list
    Word  string // the word that caused the parse error
    Err   error  // original error, if any
}

func (e *ParseError) String() string {
    return fmt.Sprintf("pkg parse: error parsing %q as int", e.Word)
}

func Parse(input string) (numbers []int, err error) {
    defer func() {
        if r := recover(); r != nil {
            if e, ok := r.(error); ok {
                err = e
            } else {
                err = fmt.Errorf("pkg: %v", r)
            }
        }
    }()
    fields := strings.Fields(input)
    numbers = fields2numbers(fields)
    return
}

func fields2numbers(fields []string) (numbers []int) {
    if len(fields) == 0 {
        panic("no words to parse")
    }
    for idx, field := range fields {
        num, err := strconv.Atoi(field)
        if err != nil {
            panic(&ParseError{idx, field, err})
        }
        numbers = append(numbers, num)
    }
    return
}

Closure‑based error handling pattern

When all functions share the same signature (e.g., HTTP handlers), a helper can wrap them with defer / recover logic, reducing repetitive error checks.

func check(err error) {
    if err != nil {
        panic(err)
    }
}

func errorHandler(fn fType1) fType1 {
    return func(a type1, b type2) {
        defer func() {
            if e, ok := recover().(error); ok {
                log.Printf("runtime panic: %v", e)
            }
        }()
        fn(a, b)
    }
}

By calling check(err) after each operation, all errors are recovered and logged uniformly.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GoError Handlingpanicrecover
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.