Panic recovery made simple
MIT License
This Go library provides a flexible way to handle panics across your application, including in goroutines. It allows for custom error handling, dumping errors to a file, optionally exiting the program after a panic occurs, including system information in crash reports, and managing crash reports.
go get github.com/leaanthony/adfer
package main
import (
"github.com/leaanthony/adfer"
)
func main() {
ph := adfer.New(adfer.Options{
DumpToFile: true,
FilePath: "crash_reports.json",
})
defer ph.Recover()
// Your code here
panic("Oh no!")
}
package main
import (
"fmt"
"github.com/leaanthony/adfer"
)
func main() {
ph := adfer.New(adfer.Options{
DumpToFile: true,
FilePath: "crash_reports.json",
ExitOnPanic: true,
IncludeSystemInfo: true,
Metadata: map[string]string{"version": "1.0.0"},
WipeFile: true,
ErrorHandler: customErrorHandler,
})
// Safe goroutine execution
ph.SafeGo(func() {
// Your code here
panic("Goroutine panic!")
})
// Retrieve last 5 crash reports
reports, err := ph.GetLastNCrashReports(5)
if err != nil {
fmt.Printf("Error retrieving crash reports: %v\n", err)
}
// Wipe crash file
err = ph.WipeCrashFile()
if err != nil {
fmt.Printf("Error wiping crash file: %v\n", err)
}
}
func customErrorHandler(err error, stack []byte) {
fmt.Printf("Custom error handler:\nError: %v\nStack:\n%s\n", err, stack)
}
CrashReport
: Represents a single crash reportSystemInfo
: Represents system informationErrorHandler
: Function type for custom error handlingOptions
: Configuration options for panic handlingPanicHandler
: Main struct for panic handlingNew(options Options) *PanicHandler
: Creates a new PanicHandler(ph *PanicHandler) Recover()
: Recovers from panics(ph *PanicHandler) SafeGo(f func())
: Executes a function in a goroutine with panic recovery(ph *PanicHandler) GetLastNCrashReports(n int) ([]CrashReport, error)
: Retrieves the last N crash reports(ph *PanicHandler) WipeCrashFile() error
: Clears all crash reports from the log fileContributions are welcome! Please feel free to submit a Pull Request.
It is Welsh for "Recover" as well as a few other meanings.
This project is licensed under the MIT License - see the LICENSE file for details.