Skip to content

Commit 82c0250

Browse files
committed
better handling of errors
1 parent 28743d9 commit 82c0250

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

packages/astro/src/server/middleware.ts

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -184,22 +184,33 @@ async function instrumentRequest(
184184

185185
const newResponseStream = new ReadableStream({
186186
start: async controller => {
187+
// Assign to a new variable to avoid TS losing the narrower type checked above.
188+
const body = originalBody;
189+
190+
async function* bodyReporter(): AsyncGenerator<string | Buffer> {
191+
try {
192+
for await (const chunk of body) {
193+
yield chunk;
194+
}
195+
} catch (e) {
196+
// Report stream errors coming from user code or Astro rendering.
197+
sendErrorToSentry(e);
198+
throw e;
199+
}
200+
}
201+
202+
const reportedBody = bodyReporter();
203+
187204
try {
188-
for await (const chunk of originalBody) {
205+
for await (const chunk of reportedBody) {
189206
const html = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
190207
const modifiedHtml = addMetaTagToHead(html);
191208
controller.enqueue(new TextEncoder().encode(modifiedHtml));
192209
}
193210
} catch (e) {
194-
sendErrorToSentry(e);
195211
controller.error(e);
196212
} finally {
197-
// try catch this, as it could have been manually closed by a user-land middleware
198-
try {
199-
controller.close();
200-
} catch {
201-
// we assume this means it was already closed
202-
}
213+
controller.close();
203214
}
204215
},
205216
});

0 commit comments

Comments
 (0)