NetLife Guru

Open source Go packages for fast, maintainable web systems. Built with a documentation-first approach.

Product
OverviewGolang packagesNews
Documentation
DocumentationGo LoggerGo RouterGo DB Form
Company
OverviewContactNewsGitHub
Community / Support
Supportinfo@netlife.guru
© 2026 NetLife Guru. All rights reserved.
GitHubinfo@netlife.guru
NetLife GuruNetLife GuruNetLife Guru
NetLife GuruNetLife GuruNetLife Guru
OverviewDocumentationNewsSupportContact

Golang packages

About
LoggingHealth ChecksProfilingMulti-Server SupportStatic FilesRate LimitingPanic RecoveryCustom 404 HandlerCustom 404 PageError Handling
RouterFeatures

Panic Recovery

Handle panics from route handlers safely using a custom recovery handler and fail-safe internal recovery.

The router package can recover from panics that occur inside route handlers.

This allows the server to keep running and return a controlled response instead of crashing the application process.

Recovery is useful for:

  • preventing unexpected handler panics from terminating the server
  • returning custom 500 Internal Server Error responses
  • logging panic details
  • keeping production services available during unexpected failures

Custom Recovery Handler

Register a custom recovery handler using r.Recovery.

r.Recovery(func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
	w.WriteHeader(http.StatusInternalServerError)
	_, _ = w.Write([]byte("Custom Internal Server Error"))
})

This handler is executed whenever a panic occurs inside a route handler.


Example

package main

import (
	"log/slog"
	"net/http"
	"os"

	"github.com/netlifeguru/router"
)

func main() {
	r := router.New()

	r.Recovery(func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
		w.WriteHeader(http.StatusInternalServerError)
		_, _ = w.Write([]byte("Custom Internal Server Error: Don't worry, we caught the panic!"))
	})

	r.HandleFunc("/", "ANY", func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
		panic("Something went terribly wrong")
	})

	if err := r.ListenAndServe(":8000"); err != nil {
		slog.Error("failed to start server", "error", err)
		os.Exit(1)
	}
}

Run the application:

go run .

Test the route:

curl http://localhost:8000/

Expected response:

Custom Internal Server Error: Don't worry, we caught the panic!

Fail-Safe Recovery

The router also protects the recovery handler itself.

If the custom recovery handler panics, the router catches that panic as well and returns a standard internal server error response.

This prevents a broken recovery handler from crashing or hanging the application.

Example:

r.Recovery(func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
	panic("recovery handler failed")
})

In this case, the router falls back to a safe 500 Internal Server Error response.


Panic Logging

When a panic occurs, the router logs the panic through Go’s standard log/slog package.

If a custom logger such as github.com/netlifeguru/logger is configured, panic logs follow the active logger configuration.

This means panic logs can be written to:

  • terminal output
  • structured JSON files
  • rotated log files
  • any custom slog.Handler

Notes

Recovery only handles panics that occur during request handling.

It does not replace normal error handling for expected application errors. Use explicit error responses for known validation, authorization, or business logic failures.

Rate Limiting

Protect routes from excessive traffic using IP and route-based request throttling middleware.

Custom 404 Handler

Override the default 404 response with a custom handler for inline HTML, localized messages, JSON responses, or lightweight fallback pages.

On this page

Custom Recovery HandlerExampleFail-Safe RecoveryPanic LoggingNotes