Skip to content

Commit 2c50d74

Browse files
authored
fix(astro): Handle errors in middlewares better (#16693)
Hopefully fixes #16491 I could not get a reproducing test there for this 🤔 I figure this is "safe" to do, but not quite sure how/when this would happen. I would assume this was "introduced" by #15995, maybe @Fryuni has a clue how/when that could happen and if this is a reasonable change 🤔
1 parent 9c6852a commit 2c50d74

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

packages/astro/src/server/middleware.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,14 +184,28 @@ 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+
187202
try {
188-
for await (const chunk of originalBody) {
203+
for await (const chunk of bodyReporter()) {
189204
const html = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
190205
const modifiedHtml = addMetaTagToHead(html);
191206
controller.enqueue(new TextEncoder().encode(modifiedHtml));
192207
}
193208
} catch (e) {
194-
sendErrorToSentry(e);
195209
controller.error(e);
196210
} finally {
197211
controller.close();

0 commit comments

Comments
 (0)