Skip to content

Commit 5b40979

Browse files
author
Sahar Shemesh
committed
fix: improve error handling and add guard check to deserializeMessage
1 parent 2a55dfd commit 5b40979

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/shared/stdio.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,10 @@ test('should be reusable after clearing', () => {
3333
readBuffer.append(Buffer.from('\n'));
3434
expect(readBuffer.readMessage()).toEqual(testMessage);
3535
});
36+
37+
test('should override invalid messages and return null', () => {
38+
const readBuffer = new ReadBuffer();
39+
40+
readBuffer.append(Buffer.from('invalid message\n'));
41+
expect(readBuffer.readMessage()).toBeNull();
42+
});

src/shared/stdio.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ZodError } from 'zod';
12
import { JSONRPCMessage, JSONRPCMessageSchema } from '../types.js';
23

34
/**
@@ -30,8 +31,16 @@ export class ReadBuffer {
3031
}
3132
}
3233

33-
export function deserializeMessage(line: string): JSONRPCMessage {
34-
return JSONRPCMessageSchema.parse(JSON.parse(line));
34+
export function deserializeMessage(line: string): JSONRPCMessage | null {
35+
try {
36+
return JSONRPCMessageSchema.parse(JSON.parse(line));
37+
} catch (error: unknown) {
38+
// When Non JSONRPC message is received (parsing error or schema validation error), return null
39+
if (error instanceof ZodError || error instanceof SyntaxError) {
40+
return null;
41+
}
42+
throw error;
43+
}
3544
}
3645

3746
export function serializeMessage(message: JSONRPCMessage): string {

0 commit comments

Comments
 (0)