未验证 提交 0d2f421c 编写于 作者: V Vijay Krishnavanshi 提交者: GitHub

feat: error handler treat err.statusCode as the same as err.status (#1460)

上级 faeaff5c
......@@ -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);
},
......
......@@ -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', () => {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册