Skip to content

Commit

Permalink
Merge pull request #142 from ksysoev/improve_panic_handling
Browse files Browse the repository at this point in the history
Implement panic recovery and enhance error logging in Dispatch method
  • Loading branch information
ksysoev authored Nov 23, 2024
2 parents 8ba3ce3 + 65a47ca commit bebbb8f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
13 changes: 12 additions & 1 deletion dispatch/router_dipatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package dispatch
import (
"fmt"
"log/slog"
"runtime/debug"

"github.com/ksysoev/wasabi"
)
Expand Down Expand Up @@ -44,6 +45,16 @@ func (d *RouterDispatcher) AddBackend(backend wasabi.RequestHandler, routingKeys
// determining the appropriate backend, and handling the request using middleware.
// If an error occurs during handling, it is logged.
func (d *RouterDispatcher) Dispatch(conn wasabi.Connection, msgType wasabi.MessageType, data []byte) {
defer func() {
if r := recover(); r != nil {
slog.Error(
"Panic during request handling",
slog.Any("error", r),
slog.String("stack", string(debug.Stack())),
)
}
}()

req := d.parser(conn, conn.Context(), msgType, data)

if req == nil {
Expand All @@ -57,7 +68,7 @@ func (d *RouterDispatcher) Dispatch(conn wasabi.Connection, msgType wasabi.Messa

err := d.useMiddleware(backend).Handle(conn, req)
if err != nil {
slog.Error("Error handling request: " + err.Error())
slog.Error("Error handling request", slog.Any("error", err), slog.String("routing_key", req.RoutingKey()))
}
}

Expand Down
18 changes: 18 additions & 0 deletions dispatch/router_dipatcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/ksysoev/wasabi"
"github.com/ksysoev/wasabi/mocks"
"github.com/stretchr/testify/assert"
)

func TestNewRouterDispatcher(t *testing.T) {
Expand Down Expand Up @@ -185,3 +186,20 @@ func TestRouterDispatcher_UseMiddleware(t *testing.T) {
t.Errorf("Expected error %v, but got %v", testError, err)
}
}

func TestRouterDispatcher_PanicHandling(t *testing.T) {
ctx := context.Background()

mockConn := mocks.NewMockConnection(t)
mockConn.EXPECT().Context().Return(ctx)

defaultBackend := mocks.NewMockBackend(t)
parser := func(_ wasabi.Connection, _ context.Context, _ wasabi.MessageType, _ []byte) wasabi.Request {
panic("test panic")
}
dispatcher := NewRouterDispatcher(defaultBackend, parser)

assert.NotPanics(t, func() {
dispatcher.Dispatch(mockConn, wasabi.MsgTypeText, []byte("test data"))
})
}

0 comments on commit bebbb8f

Please sign in to comment.