File tree 2 files changed +48
-4
lines changed
2 files changed +48
-4
lines changed Original file line number Diff line number Diff line change @@ -143,16 +143,18 @@ const proto = module.exports = {
143
143
// force text/plain
144
144
this . type = 'text' ;
145
145
146
+ let statusCode = err . status || err . statusCode ;
147
+
146
148
// ENOENT support
147
- if ( 'ENOENT' === err . code ) err . status = 404 ;
149
+ if ( 'ENOENT' === err . code ) statusCode = 404 ;
148
150
149
151
// default to 500
150
- if ( 'number' !== typeof err . status || ! statuses [ err . status ] ) err . status = 500 ;
152
+ if ( 'number' !== typeof statusCode || ! statuses [ statusCode ] ) statusCode = 500 ;
151
153
152
154
// respond
153
- const code = statuses [ err . status ] ;
155
+ const code = statuses [ statusCode ] ;
154
156
const msg = err . expose ? err . message : code ;
155
- this . status = err . status ;
157
+ this . status = err . status = statusCode ;
156
158
this . length = Buffer . byteLength ( msg ) ;
157
159
res . end ( msg ) ;
158
160
} ,
Original file line number Diff line number Diff line change @@ -100,6 +100,48 @@ describe('ctx.onerror(err)', () => {
100
100
. expect ( 200 , ( ) => { } ) ;
101
101
} ) ;
102
102
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
+
103
145
describe ( 'when invalid err.status' , ( ) => {
104
146
describe ( 'not number' , ( ) => {
105
147
it ( 'should respond 500' , ( ) => {
You can’t perform that action at this time.
0 commit comments