Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,12 @@ var (
// ErrNotAnInterface is returned when a type is not an interface.
ErrNotAnInterface = errors.New("not an interface")
)

type PanicError struct {
error
backtrace string
}

func (e *PanicError) Backtrace() string {
return e.backtrace
}
11 changes: 10 additions & 1 deletion services.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pal

import (
"context"
"fmt"
)

func runService(ctx context.Context, name string, instance any, p *Pal) error {
Expand All @@ -11,7 +12,7 @@ func runService(ctx context.Context, name string, instance any, p *Pal) error {
return nil
}

return tryWrap(func() error {
err := tryWrap(func() error {
logger.Debug("Running")
err := runner.Run(ctx)
if err != nil {
Expand All @@ -22,6 +23,14 @@ func runService(ctx context.Context, name string, instance any, p *Pal) error {
logger.Debug("Runner finished successfully")
return nil
})()

if err != nil {
if panicErr, ok := err.(*PanicError); ok {
fmt.Printf("panic: %s\n%s\n", panicErr.Error(), panicErr.Backtrace())
}
}

return err
}

func healthcheckService[T any](ctx context.Context, name string, instance T, hook LifecycleHook[T], p *Pal) error {
Expand Down
29 changes: 29 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package pal
import (
"fmt"
"reflect"
"runtime"
"strings"
)

func empty[T any]() T {
Expand All @@ -25,9 +27,36 @@ func tryWrap(f func() error) func() error {
default:
err = fmt.Errorf("%v", x)
}

err = &PanicError{
error: err,
backtrace: backtrace(4),
}
}
}()
err = f()
return
}
}

func backtrace(skipLastN int) string {
pc := make([]uintptr, 100)
n := runtime.Callers(skipLastN, pc)

pc = pc[:n]

var stackTrace strings.Builder

frames := runtime.CallersFrames(pc)

for {
frame, more := frames.Next()
stackTrace.WriteString(fmt.Sprintf("%s\n\t%s:%d\n", frame.Function, frame.File, frame.Line))

if !more {
break
}
}

return stackTrace.String()
}