Catch errors that occur within the stream in the Node adapter (#6935)

* Catch errors that occur within the stream in the Node adapter

* Adding a changeset

* Better error message on completely uncaught errors within the stream

* Update test
This commit is contained in:
Matthew Phillips 2023-05-01 10:08:18 -04:00 committed by GitHub
parent 649d70934e
commit c405cef647
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 76 additions and 2 deletions

View file

@ -0,0 +1,5 @@
---
'@astrojs/node': patch
---
Catch errors that occur within the stream in the Node adapter

View file

@ -51,8 +51,13 @@ async function writeWebResponse(app: NodeApp, res: ServerResponse, webResponse:
res.writeHead(status, Object.fromEntries(headers.entries())); res.writeHead(status, Object.fromEntries(headers.entries()));
if (webResponse.body) { if (webResponse.body) {
for await (const chunk of responseIterator(webResponse) as unknown as Readable) { try {
res.write(chunk); for await (const chunk of responseIterator(webResponse) as unknown as Readable) {
res.write(chunk);
}
} catch(err: any) {
console.error(err?.stack || err?.message || String(err))
res.write('Internal server error');
} }
} }
res.end(); res.end();

View file

@ -0,0 +1,33 @@
import nodejs from '../dist/index.js';
import { loadFixture } from './test-utils.js';
import { expect } from 'chai';
import * as cheerio from 'cheerio';
describe('Errors', () => {
let fixture;
before(async () => {
fixture = await loadFixture({
root: './fixtures/errors/',
output: 'server',
adapter: nodejs({ mode: 'standalone' }),
});
await fixture.build();
});
describe('Within the stream', async () => {
let devPreview;
before(async () => {
devPreview = await fixture.preview();
});
after(async () => {
await devPreview.stop();
});
it('when mode is standalone', async () => {
const res = await fixture.fetch('/in-stream');
const html = await res.text();
const $ = cheerio.load(html);
expect($('p').text().trim()).to.equal('Internal server error');
});
});
});

View file

@ -0,0 +1,9 @@
{
"name": "@test/nodejs-errors",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*",
"@astrojs/node": "workspace:*"
}
}

View file

@ -0,0 +1,13 @@
---
---
<html>
<head>
<title>One</title>
</head>
<body>
<h1>One</h1>
<p>
{Promise.reject('Error in the stream')}
</p>
</body>
</html>

View file

@ -4321,6 +4321,15 @@ importers:
specifier: workspace:* specifier: workspace:*
version: link:../../../../../astro version: link:../../../../../astro
packages/integrations/node/test/fixtures/errors:
dependencies:
'@astrojs/node':
specifier: workspace:*
version: link:../../..
astro:
specifier: workspace:*
version: link:../../../../../astro
packages/integrations/node/test/fixtures/node-middleware: packages/integrations/node/test/fixtures/node-middleware:
dependencies: dependencies:
'@astrojs/node': '@astrojs/node':