From 7d9dca46d2b458e673dc95eda9b54fe314a66a85 Mon Sep 17 00:00:00 2001 From: Vijay Krishnavanshi Date: Fri, 15 May 2020 12:20:56 +0530 Subject: [PATCH 1/2] fix: Koa.js handling of node.js set error codes Fixes issue: #1451 --- lib/context.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/context.js b/lib/context.js index caee62718..39ec19bf7 100644 --- a/lib/context.js +++ b/lib/context.js @@ -143,16 +143,18 @@ const proto = module.exports = { // force text/plain this.type = 'text'; + let statusCode = err.status || err.statusCode; + // ENOENT support - if ('ENOENT' == err.code) err.status = 404; + if ('ENOENT' == err.code) statusCode = 404; // default to 500 - if ('number' != typeof err.status || !statuses[err.status]) err.status = 500; + if ('number' != typeof statusCode || !statuses[statusCode]) statusCode = 500; // respond - const code = statuses[err.status]; + const code = statuses[statusCode]; const msg = err.expose ? err.message : code; - this.status = err.status; + this.status = err.status = statusCode; this.length = Buffer.byteLength(msg); res.end(msg); }, From ce9133a34027eee06667cde8afea2273d41a4a3f Mon Sep 17 00:00:00 2001 From: Vijay Krishnavanshi Date: Sun, 17 May 2020 19:38:58 +0530 Subject: [PATCH 2/2] test: Koa.js handling of node.js set error codes --- test/context/onerror.js | 42 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/test/context/onerror.js b/test/context/onerror.js index e4b8e6c80..4e59b5f3d 100644 --- a/test/context/onerror.js +++ b/test/context/onerror.js @@ -100,6 +100,48 @@ describe('ctx.onerror(err)', () => { .expect(200, () => {}); }); + it('should set status specified in the error using statusCode', () => { + const app = new Koa(); + + app.use((ctx, next) => { + ctx.body = 'something else'; + const err = new Error('Not found'); + err.statusCode = 404; + throw err; + }); + + const server = app.listen(); + + return request(server) + .get('/') + .expect(404) + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect('Not Found'); + }); + + describe('when invalid err.statusCode', () => { + describe('not number', () => { + it('should respond 500', () => { + const app = new Koa(); + + app.use((ctx, next) => { + ctx.body = 'something else'; + const err = new Error('some error'); + err.statusCode = 'notnumber'; + throw err; + }); + + const server = app.listen(); + + return request(server) + .get('/') + .expect(500) + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect('Internal Server Error'); + }); + }); + }); + describe('when invalid err.status', () => { describe('not number', () => { it('should respond 500', () => {