goext/langext/panic.go

75 lines
1.4 KiB
Go
Raw Permalink Normal View History

2023-04-26 11:34:46 +02:00
package langext
2023-09-27 14:15:59 +02:00
import "runtime/debug"
2023-04-26 11:34:46 +02:00
type PanicWrappedErr struct {
panic any
2023-09-27 14:15:59 +02:00
Stack string
2023-04-26 11:34:46 +02:00
}
func (p PanicWrappedErr) Error() string {
return "A panic occured"
}
2024-10-13 16:10:55 +02:00
func (p PanicWrappedErr) RecoveredObj() any {
2023-04-26 11:34:46 +02:00
return p.panic
}
2023-04-26 11:35:28 +02:00
func RunPanicSafe(fn func()) (err error) {
2023-04-26 11:34:46 +02:00
defer func() {
if rec := recover(); rec != nil {
2023-09-27 14:15:59 +02:00
err = PanicWrappedErr{panic: rec, Stack: string(debug.Stack())}
2023-04-26 11:34:46 +02:00
}
}()
fn()
return nil
}
2023-04-26 11:35:28 +02:00
func RunPanicSafeR1(fn func() error) (err error) {
2023-04-26 11:34:46 +02:00
defer func() {
if rec := recover(); rec != nil {
2023-09-27 14:15:59 +02:00
err = PanicWrappedErr{panic: rec, Stack: string(debug.Stack())}
2023-04-26 11:34:46 +02:00
}
}()
return fn()
}
2023-04-26 11:35:28 +02:00
func RunPanicSafeR2[T1 any](fn func() (T1, error)) (r1 T1, err error) {
2023-04-26 11:34:46 +02:00
defer func() {
if rec := recover(); rec != nil {
r1 = *new(T1)
2023-09-27 14:15:59 +02:00
err = PanicWrappedErr{panic: rec, Stack: string(debug.Stack())}
2023-04-26 11:34:46 +02:00
}
}()
return fn()
}
2023-04-26 11:35:28 +02:00
func RunPanicSafeR3[T1 any, T2 any](fn func() (T1, T2, error)) (r1 T1, r2 T2, err error) {
2023-04-26 11:34:46 +02:00
defer func() {
if rec := recover(); rec != nil {
r1 = *new(T1)
r2 = *new(T2)
2023-09-27 14:15:59 +02:00
err = PanicWrappedErr{panic: rec, Stack: string(debug.Stack())}
2023-04-26 11:34:46 +02:00
}
}()
return fn()
}
2023-04-26 11:35:28 +02:00
func RunPanicSafeR4[T1 any, T2 any, T3 any](fn func() (T1, T2, T3, error)) (r1 T1, r2 T2, r3 T3, err error) {
2023-04-26 11:34:46 +02:00
defer func() {
if rec := recover(); rec != nil {
r1 = *new(T1)
r2 = *new(T2)
r3 = *new(T3)
2023-09-27 14:15:59 +02:00
err = PanicWrappedErr{panic: rec, Stack: string(debug.Stack())}
2023-04-26 11:34:46 +02:00
}
}()
return fn()
}