Skip to content

Commit 0d2f421

Browse files
feat: error handler treat err.statusCode as the same as err.status (#1460)
1 parent faeaff5 commit 0d2f421

File tree

2 files changed

+48
-4
lines changed

2 files changed

+48
-4
lines changed

lib/context.js

+6-4
Original file line numberDiff line numberDiff line change
@@ -143,16 +143,18 @@ const proto = module.exports = {
143143
// force text/plain
144144
this.type = 'text';
145145

146+
let statusCode = err.status || err.statusCode;
147+
146148
// ENOENT support
147-
if ('ENOENT' === err.code) err.status = 404;
149+
if ('ENOENT' === err.code) statusCode = 404;
148150

149151
// default to 500
150-
if ('number' !== typeof err.status || !statuses[err.status]) err.status = 500;
152+
if ('number' !== typeof statusCode || !statuses[statusCode]) statusCode = 500;
151153

152154
// respond
153-
const code = statuses[err.status];
155+
const code = statuses[statusCode];
154156
const msg = err.expose ? err.message : code;
155-
this.status = err.status;
157+
this.status = err.status = statusCode;
156158
this.length = Buffer.byteLength(msg);
157159
res.end(msg);
158160
},

test/context/onerror.js

+42
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,48 @@ describe('ctx.onerror(err)', () => {
100100
.expect(200, () => {});
101101
});
102102

103+
it('should set status specified in the error using statusCode', () => {
104+
const app = new Koa();
105+
106+
app.use((ctx, next) => {
107+
ctx.body = 'something else';
108+
const err = new Error('Not found');
109+
err.statusCode = 404;
110+
throw err;
111+
});
112+
113+
const server = app.listen();
114+
115+
return request(server)
116+
.get('/')
117+
.expect(404)
118+
.expect('Content-Type', 'text/plain; charset=utf-8')
119+
.expect('Not Found');
120+
});
121+
122+
describe('when invalid err.statusCode', () => {
123+
describe('not number', () => {
124+
it('should respond 500', () => {
125+
const app = new Koa();
126+
127+
app.use((ctx, next) => {
128+
ctx.body = 'something else';
129+
const err = new Error('some error');
130+
err.statusCode = 'notnumber';
131+
throw err;
132+
});
133+
134+
const server = app.listen();
135+
136+
return request(server)
137+
.get('/')
138+
.expect(500)
139+
.expect('Content-Type', 'text/plain; charset=utf-8')
140+
.expect('Internal Server Error');
141+
});
142+
});
143+
});
144+
103145
describe('when invalid err.status', () => {
104146
describe('not number', () => {
105147
it('should respond 500', () => {

0 commit comments

Comments
 (0)