Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit e7d8e25

Browse files
committedMay 17, 2023
Catch errors when logging requests
If Miniflare is disposed before `workerd` finishes sending a request log, incomplete JSON-data may be sent, which will cause an error. This change catches errors when parsing request logs since it's not too important if these aren't logged.

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed
 

‎packages/miniflare/src/index.ts

+11-1
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import {
6565
Mutex,
6666
NoOpLog,
6767
OptionalZodTypeOf,
68+
ResponseInfoSchema,
6869
Timers,
6970
defaultTimers,
7071
formatResponse,
@@ -580,7 +581,16 @@ export class Miniflare {
580581
request
581582
);
582583
} else if (url.pathname === "/core/log") {
583-
this.#log.info(await formatResponse(request));
584+
const text = await request.text();
585+
try {
586+
// `JSON.parse()`ing may fail if the request was aborted and a partial
587+
// body was received
588+
const info = ResponseInfoSchema.parse(JSON.parse(text));
589+
this.#log.info(await formatResponse(info));
590+
} catch (e: unknown) {
591+
this.#log.debug(`Error parsing response log: ${String(e)}`);
592+
}
593+
response = new Response(null, { status: 204 });
584594
} else {
585595
// TODO: check for proxying/outbound fetch header first (with plans for fetch mocking)
586596
response = await this.#handleLoopbackPlugins(request, url);

‎packages/miniflare/src/shared/log.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import {
1111
yellow,
1212
} from "kleur/colors";
1313
import { z } from "zod";
14-
import { Request } from "../http";
1514
import { LogLevel } from "../workers";
1615

1716
const cwd = process.cwd();
@@ -130,16 +129,16 @@ export class NoOpLog extends Log {
130129
}
131130
}
132131

133-
const ResponseInfoSchema = z.object({
132+
export const ResponseInfoSchema = z.object({
134133
status: z.number(),
135134
statusText: z.string(),
136135
method: z.string(),
137136
url: z.string(),
138137
time: z.number(),
139138
});
139+
export type ResponseInfo = z.infer<typeof ResponseInfoSchema>;
140140

141-
export async function formatResponse(request: Request) {
142-
const info = ResponseInfoSchema.parse(await request.json());
141+
export async function formatResponse(info: ResponseInfo) {
143142
const url = new URL(info.url);
144143

145144
const lines = [

0 commit comments

Comments
 (0)
This repository has been archived.