diff --git a/src/middlewares/har.ts b/src/middlewares/har.ts index e4dd002..dd0f93c 100644 --- a/src/middlewares/har.ts +++ b/src/middlewares/har.ts @@ -17,15 +17,29 @@ export const HarMiddleware = (req: Request, res: Response, next: NextFunction) = return originalSend.call(this, body); }; - res.once('finish', () => { - const HarEntry: Partial = { - time: Date.now() - requestStartTime.getTime(), - startedDateTime: requestStartTimeStamp, - request: buildHarRequest(req), - response: buildHarResponse(res, { body: responseBody }), - } + res.once('finish', async () => { + try { + const mockId = res.locals.rq_metadata?.mockId; + // No matching mock (e.g. 404) means there's nothing to attach the log to. + if (!mockId) { + return; + } + + const HarEntry: Partial = { + time: Date.now() - requestStartTime.getTime(), + startedDateTime: requestStartTimeStamp, + request: buildHarRequest(req), + response: buildHarResponse(res, { body: responseBody }), + } - storageService.storeLog({ mockId: res.locals.rq_metadata.mockId, HarEntry, }) + // Await so a rejected storeLog is caught here rather than surfacing + // as an unhandled rejection. + await storageService.storeLog({ mockId, HarEntry, }) + } catch (error) { + // Never let a logging failure escape the finish handler — it would + // surface as an uncaught exception and can crash the process. + console.error("[HarMiddleware] Failed to store log", error); + } }); next();