From 0aa6310971ec756695b9fbe96ef8622d700035e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Wed, 26 Apr 2023 11:34:46 +0200 Subject: [PATCH] v0.0.106 --- langext/panic.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 langext/panic.go diff --git a/langext/panic.go b/langext/panic.go new file mode 100644 index 0000000..36e04c5 --- /dev/null +++ b/langext/panic.go @@ -0,0 +1,71 @@ +package langext + +type PanicWrappedErr struct { + panic any +} + +func (p PanicWrappedErr) Error() string { + return "A panic occured" +} + +func (p PanicWrappedErr) ReoveredObj() any { + return p.panic +} + +func runPanicSafe(fn func()) (err error) { + defer func() { + if rec := recover(); rec != nil { + err = PanicWrappedErr{panic: rec} + } + }() + + fn() + + return nil +} + +func runPanicSafeR1(fn func() error) (err error) { + defer func() { + if rec := recover(); rec != nil { + err = PanicWrappedErr{panic: rec} + } + }() + + return fn() +} + +func runPanicSafeR2[T1 any](fn func() (T1, error)) (r1 T1, err error) { + defer func() { + if rec := recover(); rec != nil { + r1 = *new(T1) + err = PanicWrappedErr{panic: rec} + } + }() + + return fn() +} + +func runPanicSafeR3[T1 any, T2 any](fn func() (T1, T2, error)) (r1 T1, r2 T2, err error) { + defer func() { + if rec := recover(); rec != nil { + r1 = *new(T1) + r2 = *new(T2) + err = PanicWrappedErr{panic: rec} + } + }() + + return fn() +} + +func runPanicSafeR4[T1 any, T2 any, T3 any](fn func() (T1, T2, T3, error)) (r1 T1, r2 T2, r3 T3, err error) { + defer func() { + if rec := recover(); rec != nil { + r1 = *new(T1) + r2 = *new(T2) + r3 = *new(T3) + err = PanicWrappedErr{panic: rec} + } + }() + + return fn() +}