Skip to content

Commit

Permalink
Merge PR #13 from 'nodech/statuscode-400'
Browse files Browse the repository at this point in the history
  • Loading branch information
nodech committed Apr 13, 2023
2 parents bb0ba36 + 0338e4d commit ef16fb0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
3 changes: 3 additions & 0 deletions lib/middleware/bodyparser.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ function bodyParser(options) {
try {
req.resume();
req.body = await parseBody(req, opt);
} catch (err) {
err.statusCode = 400;
throw err;
} finally {
req.pause();
}
Expand Down
36 changes: 35 additions & 1 deletion test/http-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ describe('HTTP/1.1 Tests', function() {

client = new Client();

// NOTE: Body parser will no longer throw errors
// when connection is closed on TIMEOUT.
//
// request.pause() -> request.resume() -> request.pause() will
// actually no longer throw errors ,
// where just request.pause() (without body parser) will.
// TODO: Find the cause and also, maybe add wrapped request error handler.
//
// NOTE: Check note below about request.
server.use(server.bodyParser({
type: 'json'
}));

server.use(server.router());
});

Expand All @@ -39,7 +52,9 @@ describe('HTTP/1.1 Tests', function() {
});

afterEach(async () => {
await server.close();
if (server.opened)
await server.close();

seen = false;
});

Expand Down Expand Up @@ -207,6 +222,7 @@ describe('HTTP/1.1 Tests', function() {
let closed = null;

/**
* NOTE: Body parser above.
* NOTE:
* Error event on abort was introduces in Node.js v15
* So anything below wont throw an error on request.
Expand Down Expand Up @@ -262,4 +278,22 @@ describe('HTTP/1.1 Tests', function() {

assert.strictEqual(closed, true);
});

it('should return 400 on incorrect request body', async () => {
server.post('/badjson', async (req, res) => {
seen = true;
return res.end();
});

await client.request({
hostname: '127.0.0.1',
port: PORT,
method: 'POST',
path: '/badjson',
data: '{ "badjson": }'
}, [
resDeepEqual('statusCode', 400),
resDeepEqual('statusMessage', 'Bad Request')
]);
});
});

0 comments on commit ef16fb0

Please sign in to comment.