Skip to content

Commit 2d128c3

Browse files
authored
fix: fix nil pointer dereference error in error handler (#109)
Signed-off-by: Alexander Matyushentsev <[email protected]>
1 parent 162a6c3 commit 2d128c3

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

internal/protocol/protocol.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ func (p *Protocol) handleCancelledNotification(notification *transport.BaseJSONR
344344
}
345345

346346
func (p *Protocol) handleResponse(response *transport.BaseJSONRPCResponse, errResp *transport.BaseJSONRPCError) {
347-
var id = response.Id
347+
var id transport.RequestId
348348
var result interface{}
349349
var err error
350350

@@ -354,6 +354,7 @@ func (p *Protocol) handleResponse(response *transport.BaseJSONRPCResponse, errRe
354354
} else {
355355
// Parse the response
356356
result = response.Result
357+
id = response.Id
357358
}
358359

359360
p.mu.RLock()

internal/protocol/protocol_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,51 @@ func TestProtocol_RequestHandler(t *testing.T) {
201201
}
202202
}
203203

204+
func TestProtocol_RequestHandler_ErrorResponse(t *testing.T) {
205+
p := NewProtocol(nil)
206+
tr := testingutils.NewMockTransport()
207+
208+
if err := p.Connect(tr); err != nil {
209+
t.Fatalf("Connect failed: %v", err)
210+
}
211+
212+
// Register request handler
213+
handlerCalled := false
214+
p.SetRequestHandler("test_method", func(ctx context.Context, req *transport.BaseJSONRPCRequest, extra RequestHandlerExtra) (transport.JsonRpcBody, error) {
215+
handlerCalled = true
216+
return nil, errors.New("sample error")
217+
})
218+
219+
// Simulate incoming request
220+
tr.SimulateMessage(transport.NewBaseMessageRequest(&transport.BaseJSONRPCRequest{
221+
Jsonrpc: "2.0",
222+
Method: "test_method",
223+
Params: json.RawMessage(`{"param": "value"}`),
224+
}))
225+
226+
// Give some time for handler to be called
227+
time.Sleep(50 * time.Millisecond)
228+
229+
if !handlerCalled {
230+
t.Error("Request handler was not called")
231+
}
232+
233+
// Check response
234+
msgs := tr.GetMessages()
235+
if len(msgs) != 1 {
236+
t.Fatalf("Expected 1 message, got %d", len(msgs))
237+
}
238+
239+
response := msgs[0]
240+
if response.Type != transport.BaseMessageTypeJSONRPCErrorType {
241+
t.Fatal("Message is not a response")
242+
}
243+
244+
if string(response.JsonRpcError.Error.Message) != "sample error" {
245+
t.Errorf("Expected result 'sample error', got %v", string(response.JsonRpcError.Error.Message))
246+
}
247+
}
248+
204249
// TestProtocol_NotificationHandler tests the handling of incoming notifications.
205250
// This is important for asynchronous events and status updates.
206251
// It verifies:

0 commit comments

Comments
 (0)