Fix UnrecoveredPanic: runtime error: invalid memory address or nil pointer dereference in Go
This panic occurs when code dereferences a nil pointer, and no recovery mechanism is in place to catch it. In an HTTP server, an unrecovered panic in a handler goroutine crashes only that request, but in main or background goroutines it crashes the entire process. Fix it by adding recover in background goroutines and using middleware recovery in HTTP handlers.
Reading the Stack Trace
Here's what each line means:
- main.processEvent(0x0) /app/workers/event.go:22 +0x94: The processEvent function at line 22 receives a nil pointer argument and dereferences it, causing a panic.
- runtime.gopanic({0x102840ea0, 0x1040b8900}): The Go runtime triggers a panic for the nil pointer dereference. Without a recover, this will crash the goroutine.
- created by main.(*EventWorker).Start in goroutine 1 /app/workers/event.go:12 +0x70: The goroutine was spawned by the EventWorker.Start method. Since it has no recovery, the panic is fatal.
Common Causes
1. No recover in background goroutine
A goroutine processing work items has no defer/recover, so a panic from a single item crashes the entire process.
func (w *EventWorker) Start() {
go func() {
for event := range w.events {
processEvent(event) // panic here kills the process
}
}()
}
2. Nil pointer not checked before use
A function receives a pointer that may be nil and dereferences it without a nil check.
func processEvent(e *Event) {
log.Printf("processing event: %s", e.Name) // panics if e is nil
}
3. Panic in deferred function
A panic inside a deferred function can mask the original panic and make debugging harder.
func process() {
defer cleanup() // if cleanup panics, original error is lost
// ... work that may panic ...
}
The Fix
Wrap goroutine work in a function with defer/recover to catch panics and log them with a stack trace instead of crashing the process. Add nil checks for pointer parameters. The worker continues processing subsequent events after recovering from a panic.
func (w *EventWorker) Start() {
go func() {
for event := range w.events {
processEvent(event)
}
}()
}
func processEvent(e *Event) {
log.Printf("processing event: %s", e.Name)
}
func (w *EventWorker) Start() {
go func() {
for event := range w.events {
w.safeProcess(event)
}
}()
}
func (w *EventWorker) safeProcess(event *Event) {
defer func() {
if r := recover(); r != nil {
log.Printf("recovered from panic processing event: %v\n%s", r, debug.Stack())
// optionally send to error tracking
}
}()
processEvent(event)
}
func processEvent(e *Event) {
if e == nil {
log.Println("WARNING: received nil event, skipping")
return
}
log.Printf("processing event: %s", e.Name)
}
Testing the Fix
package workers_test
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestProcessEvent_NilSafe(t *testing.T) {
assert.NotPanics(t, func() {
processEvent(nil)
})
}
func TestProcessEvent_ValidEvent(t *testing.T) {
assert.NotPanics(t, func() {
processEvent(&Event{Name: "test"})
})
}
func TestSafeProcess_RecoversPanic(t *testing.T) {
w := &EventWorker{events: make(chan *Event, 1)}
assert.NotPanics(t, func() {
w.safeProcess(nil)
})
}
func TestEventWorker_ContinuesAfterPanic(t *testing.T) {
events := make(chan *Event, 3)
w := &EventWorker{events: events}
events <- nil // will trigger nil check
events <- &Event{Name: "valid"} // should process normally
close(events)
assert.NotPanics(t, func() {
for event := range w.events {
w.safeProcess(event)
}
})
}
Run your tests:
go test ./workers/... -v
Pushing Through CI/CD
git checkout -b fix/go-panic-recovery,git add workers/event.go workers/event_test.go,git commit -m "fix: add panic recovery and nil checks in event worker goroutine",git push origin fix/go-panic-recovery
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm panic recovery works.
- Open a pull request with the recovery changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify in staging.
Frequently Asked Questions
BugStack tests with nil inputs, validates that panics are recovered and logged, and ensures the worker continues processing after a panic before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Recover in goroutines that process independent work items to prevent one bad item from killing the worker. Do not recover from panics caused by programmer errors like index out of bounds — fix those at the source.
net/http recovers from panics per-request by default. Gin and Echo have their own Recovery middleware. Background goroutines you spawn need their own recover.