How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Go · Go

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

goroutine 18 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e runtime.gopanic({0x102840ea0, 0x1040b8900}) /usr/local/go/src/runtime/panic.go:770 +0x124 main.processEvent(0x0) /app/workers/event.go:22 +0x94 main.(*EventWorker).Start.func1() /app/workers/event.go:14 +0x48 created by main.(*EventWorker).Start in goroutine 1 /app/workers/event.go:12 +0x70

Here's what each line means:

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.

Before (broken)
func (w *EventWorker) Start() {
	go func() {
		for event := range w.events {
			processEvent(event)
		}
	}()
}

func processEvent(e *Event) {
	log.Printf("processing event: %s", e.Name)
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run go test ./... locally to confirm panic recovery works.
  2. Open a pull request with the recovery changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.