Skip to content

Commit

Permalink
fix(polka): add min range check for err.status code;
Browse files Browse the repository at this point in the history
- include non-numeric `err.status` tests
- restores typeof check from #178
  • Loading branch information
lukeed committed Oct 1, 2021
1 parent 8448ac0 commit 561558b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/polka/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import Router from 'trouter';
import { parse } from '@polka/url';

function onError(err, req, res) {
let code = (res.statusCode = +err.status || 500);
let code = typeof err.status === 'number' && err.status;
code = res.statusCode = (code && code >= 100 ? code : 500);
if (typeof err === 'string' || Buffer.isBuffer(err)) res.end(err);
else res.end(err.message || http.STATUS_CODES[code]);
}
Expand Down
52 changes: 52 additions & 0 deletions packages/polka/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -984,6 +984,7 @@ test('errors – `throw Error` :: async', async () => {
app.server.close();
});


test('errors – `throw Error` :: async :: subapp', async () => {
let sub = polka().use(async () => {
throw new Error('busted');
Expand All @@ -1005,6 +1006,7 @@ test('errors – `throw Error` :: async :: subapp', async () => {
app.server.close();
});


test('errors – `throw msg`', async () => {
// t.plan(3);

Expand Down Expand Up @@ -1132,6 +1134,7 @@ test('sub-application', async () => {
app.server.close();
});


test('sub-application w/ query params', async () => {
// t.plan(12);

Expand Down Expand Up @@ -1287,6 +1290,55 @@ test('options.onError (err.status)', async () => {
});


test('options.onError (err.status) non-numeric', async () => {
function throws(status) {
return (r1, f2, next) => {
let e = Error('Oops');
e.status = status;
next(e);
};
}

function check(path, code = 500) {
return get(path).catch(err => {
assert.is(err.statusCode, code, '~> response has 500 status code');
assert.is(err.data, 'Oops', '~> response body is "Oops" string');
});
}

let app = (
polka()
.get('/null', throws(null))
.get('/string', throws('418'))
.get('/array', throws([1, 2, 3]))
.get('/undefined', throws(undefined))
.get('/200', throws(200))
.get('/101', throws(101))
.get('/99', throws(99))
.get('/1', throws(1))
.get('/0', throws(0))
);

try {
let uri = $.listen(app);

await check(uri + '/0', 500);
await check(uri + '/1', 500);
await check(uri + '/99', 500);

await check(uri + '/101', 101);
await check(uri + '/200', 200);

await check(uri + '/null', 500);
await check(uri + '/string', 500);
await check(uri + '/undefined', 500);
await check(uri + '/array', 500);
} finally {
app.server.close();
}
});


test('options.onError – custom', async () => {
// t.plan(7);

Expand Down

0 comments on commit 561558b

Please sign in to comment.