diff --git a/src/event-stream/snp-event-stream.ts b/src/event-stream/snp-event-stream.ts index 9fd253df00..3871af9631 100644 --- a/src/event-stream/snp-event-stream.ts +++ b/src/event-stream/snp-event-stream.ts @@ -59,14 +59,21 @@ export class SnpEventStreamHandler { async handleMsg(messageId: string, timestamp: string, path: string, body: any) { this.logger.debug(`Received SNP stream event ${path}, msgId: ${messageId}`); + let response; - const response = await this.eventServer.fastifyInstance.inject({ - method: 'POST', - url: path, - payload: body, - }); + try { + response = await this.eventServer.fastifyInstance.inject({ + method: 'POST', + url: path, + payload: body, + }); + } catch (error) { + const errorMessage = `Failed to process SNP message ${messageId} at path ${path}: ${error}`; + this.logger.error(error, errorMessage); + throw new Error(errorMessage); + } - if (response.statusCode < 200 || response.statusCode > 299) { + if (response?.statusCode < 200 || response?.statusCode > 299) { const errorMessage = `Failed to process SNP message ${messageId} at path ${path}, status: ${response.statusCode}, body: ${response.body}`; this.logger.error(errorMessage); throw new Error(errorMessage); diff --git a/tests/snp/snp-ingestion.test.ts b/tests/snp/snp-ingestion.test.ts index 522f4d53ae..df3c973415 100644 --- a/tests/snp/snp-ingestion.test.ts +++ b/tests/snp/snp-ingestion.test.ts @@ -127,4 +127,49 @@ describe('SNP integration tests', () => { hash: sampleEventsLastBlockHash, }); }); + + test('handleMsg throws error when inject() fails', async () => { + const snpClient = new SnpEventStreamHandler({ + db, + eventServer, + lastMessageId: '0', + }); + + const originalInject = eventServer.fastifyInstance.inject.bind(eventServer.fastifyInstance); + eventServer.fastifyInstance.inject = () => { + throw new Error('Simulated inject failure'); + }; + + await expect( + snpClient.handleMsg('test-msg-id', '2024-01-01T00:00:00Z', '/test/path', {}) + ).rejects.toThrow( + 'Failed to process SNP message test-msg-id at path /test/path: Error: Simulated inject failure' + ); + + eventServer.fastifyInstance.inject = originalInject; + }); + + test('handleMsg throws error when response status is not 200', async () => { + const snpClient = new SnpEventStreamHandler({ + db, + eventServer, + lastMessageId: '0', + }); + + const originalInject = eventServer.fastifyInstance.inject.bind(eventServer.fastifyInstance); + eventServer.fastifyInstance.inject = (() => { + return Promise.resolve({ + statusCode: 500, + body: 'Internal Server Error', + }); + }) as any; + + await expect( + snpClient.handleMsg('test-msg-id', '2024-01-01T00:00:00Z', '/test/path', {}) + ).rejects.toThrow( + 'Failed to process SNP message test-msg-id at path /test/path, status: 500, body: Internal Server Error' + ); + + eventServer.fastifyInstance.inject = originalInject; + }); });