calm

package
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package calm provides panic recovery that converts panics into errors with stack traces and an errclass.Panic classification.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Unpanic

func Unpanic(f func() error) (err error)

Unpanic executes the given function catching any panic and returning it as an error with stack trace and an errclass.Panic classification. WARNING: It is not possible to recover from a panic in a goroutine spawned by `f()`. Users should ensure that any goroutines created by `f()` are likewise guarded against panics.

Example
package main

import (
	"bytes"
	"fmt"
	"log/slog"
	"regexp"

	"github.com/wood-jp/xerrors"
	"github.com/wood-jp/xerrors/calm"
)

func newLogger(buf *bytes.Buffer) *slog.Logger {
	return slog.New(slog.NewJSONHandler(buf, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	}))
}

var (
	reSource = regexp.MustCompile(`"source":"[^"]*"`)
	reLine   = regexp.MustCompile(`"line":\d+`)
)

func normalizeStack(s string) string {
	s = reSource.ReplaceAllString(s, `"source":"..."`)
	s = reLine.ReplaceAllString(s, `"line":0`)
	return s
}

func main() {
	var buf bytes.Buffer
	err := calm.Unpanic(func() error {
		panic("something went wrong")
	})
	newLogger(&buf).Error("recovered panic", xerrors.Log(err))
	fmt.Print(normalizeStack(buf.String()))
}
Output:
{"level":"ERROR","msg":"recovered panic","error":{"error":"panic: something went wrong","error_detail":{"stacktrace":[{"func":"github.com/wood-jp/xerrors/calm_test.ExampleUnpanic.func1","line":0,"source":"..."},{"func":"github.com/wood-jp/xerrors/calm.Unpanic","line":0,"source":"..."},{"func":"github.com/wood-jp/xerrors/calm_test.ExampleUnpanic","line":0,"source":"..."},{"func":"main.main","line":0,"source":"..."}],"class":"panic"}}}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL