@@ -51,29 +51,30 @@ function finalhandler(req, res, options) {
5151 var body
5252 var constructBody
5353 var msg
54+ var status = res . statusCode
5455
5556 // unhandled error
5657 if ( err ) {
5758 // default status code to 500
58- if ( ! res . statusCode || res . statusCode < 400 ) {
59- res . statusCode = 500
59+ if ( ! status || status < 400 ) {
60+ status = 500
6061 }
6162
6263 // respect err.status
63- if ( err . status ) {
64- res . statusCode = err . status
64+ if ( err . status >= 400 && err . status < 600 ) {
65+ status = err . status
6566 }
6667
6768 // production gets a basic error message
6869 msg = stacktrace
6970 ? err . stack || String ( err )
70- : http . STATUS_CODES [ res . statusCode ]
71+ : http . STATUS_CODES [ status ]
7172 } else {
72- res . statusCode = 404
73+ status = 404
7374 msg = 'Cannot ' + req . method + ' ' + ( req . originalUrl || req . url )
7475 }
7576
76- debug ( 'default %s' , res . statusCode )
77+ debug ( 'default %s' , status )
7778
7879 // schedule onerror callback
7980 if ( err && onerror ) {
@@ -101,12 +102,13 @@ function finalhandler(req, res, options) {
101102 }
102103
103104 // construct body
104- body = constructBody ( res . statusCode , msg )
105+ body = constructBody ( status , msg )
105106
106107 // security header for content sniffing
107108 res . setHeader ( 'X-Content-Type-Options' , 'nosniff' )
108109
109110 // standard headers
111+ res . statusCode = status
110112 res . setHeader ( 'Content-Type' , body . type )
111113 res . setHeader ( 'Content-Length' , body . length )
112114
0 commit comments