Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/micro/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,14 @@ export const sendError = (
res: ServerResponse,
errorObj: Error | HttpError,
) => {
if ('statusCode' in errorObj && errorObj.statusCode) {
if (res.headersSent) {
// The status line and headers are already on the wire, so an error
// response can't be sent. Abort the connection so the client doesn't
// mistake the truncated body for a complete one.
if (!res.writableEnded) {
res.destroy();
}
} else if ('statusCode' in errorObj && errorObj.statusCode) {
send(res, errorObj.statusCode, errorObj.message);
} else send(res, 500, 'Internal Server Error');

Expand Down
21 changes: 21 additions & 0 deletions test/suite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -696,3 +696,24 @@ void test('Content-Type header for JSON is set', async (t) => {
t.equal(res.headers.get('content-type'), 'application/json; charset=utf-8');
shutdown();
});

void test('throw after the response has started does not reject run()', async (t) => {
let outcome: Promise<unknown> = Promise.resolve();
const fn: RequestHandler = (req, res) => {
res.write('partial');
throw new Error('500 from test (expected)');
};

const server = http.createServer((req, res) => {
outcome = run(req, res, fn);
});
await new Promise<void>((resolve) => {
server.listen(resolve);
});
const { port } = server.address() as AddressInfo;

const res = await fetch(`http://localhost:${port}`, { timeout: 2000 });
await res.text().catch(() => undefined);
await t.resolves(outcome);
server.close();
});