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
13 changes: 10 additions & 3 deletions packages/micro/src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Native
import { Stream, Readable } from 'stream';
import { inspect } from 'util';
// Packages
import contentType from 'content-type';
import getRawBody from 'raw-body';
Expand Down Expand Up @@ -148,9 +149,15 @@ export const run = (
}
})
.catch((err: unknown) => {
if (isError(err)) {
sendError(req, res, err);
}
// A handler can throw or reject with any value. Always answer with an
// error response, otherwise the request never completes.
sendError(
req,
res,
isError(err)
? err
: new Error(`Handler threw a non-Error value: ${inspect(err)}`),
);
});

// Maps requests to buffered raw bodies so that
Expand Down
23 changes: 23 additions & 0 deletions test/suite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -696,3 +696,26 @@ 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 (500) with a non-Error value', async (t) => {
const fn: RequestHandler = () => {
throw 'not an error object';
};

const [url, shutdown] = await startServer(fn);

const { status } = await fetch(url, { timeout: 2000 });
t.same(status, 500);
shutdown();
});

void test('rejected promise with a non-Error value sends 500', async (t) => {
// eslint-disable-next-line prefer-promise-reject-errors -- testing a non-Error rejection
const fn: RequestHandler = () => Promise.reject({ reason: 'plain object' });

const [url, shutdown] = await startServer(fn);

const { status } = await fetch(url, { timeout: 2000 });
t.same(status, 500);
shutdown();
});