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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
