luminyra
Guides

Log errors and recover from panics

Recover at a task boundary, capture a stack trace, and log the error with slog.

Recover at a task boundary

Recover runs the supplied function. If it panics, Recover returns an Error with the stack trace, error code, and task name. Use it at a boundary that can handle a failed task, such as the entry point of a background job.

errs/examples/logging/main.go
// Recover calls the function and turns a panic into an error with
// attributes and the stack of the panic; the program keeps running.
err := errs.Recover(func() {
	var counts map[string]int
	counts["alice"]++ // writing to a nil map panics
}, errs.Code.Attr("JOB_PANIC"), slog.String("job", "sync-users"))
View on GitHub

Write structured log records

When you pass the error to slog.Logger.Error, slog.LogValuer expands it into structured fields so you can inspect the message, code, and task attributes together. The example omits the timestamp and stack to keep the output stable. For diagnosis, keep the stack in the log or inspect its frames with Error.Stack.

errs/examples/logging/main.go
// *errs.Error implements slog.LogValuer, so logging it expands it into a
// group.
logger.Error("job failed", "err", err)
View on GitHub
errs/example_test.go
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
	ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
		if a.Key == slog.TimeKey || a.Key == "stacktrace" {
			return slog.Attr{} // keep the example output stable
		}
		return a
	},
}))

logger.Error("request failed", "err", errs.New("timeout", errs.Code.Attr("UPSTREAM_TIMEOUT")))
Expected output
level=ERROR msg="request failed" err.message=timeout err.code=UPSTREAM_TIMEOUT
View on GitHub

On this page