Golang / GoLang Production Patterns and Web Standards Interview Questions
How and when should you use panic and recover in production Go code?
The Go convention is clear: panics are for unrecoverable programmer errors (nil pointer dereference, index out of bounds, type assertion failure). Libraries should never let panics propagate to callers — they convert panics to errors at the public API boundary.
// Library pattern: convert internal panics to errors at the boundary func safelyParseTemplate(tmpl string) (result string, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("template parse panicked: %v", r) } }() // This might panic on invalid template syntax in some implementations result = parseTemplate(tmpl) return result, nil } // HTTP recovery middleware â catch handler panics gracefully func recoveryMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { // Log the full stack trace buf := make([]byte, 4096) n := runtime.Stack(buf, false) log.Printf("panic in %s %s: %v\n%s", r.Method, r.URL.Path, err, buf[:n]) // Return 500 to the client http.Error(w, "internal server error", http.StatusInternalServerError) } }() next.ServeHTTP(w, r) }) } // When panic IS appropriate: // 1. Programmer invariant violation that cannot be recovered func mustPositive(n int) int { if n <= 0 { panic(fmt.Sprintf("expected positive, got %d", n)) } return n } // 2. Impossible type assertion that should never fail if code is correct // 3. Test helpers: t.Fatalf is analogous â immediate stop // When NOT to use panic: // - File not found, network failure, validation errors â return error // - Any expected failure condition â return error
More Related questions...