1
1
'use strict'
2
2
3
- const { finished } = require ( 'stream' )
3
+ const { finished, PassThrough } = require ( 'stream' )
4
4
const {
5
5
InvalidArgumentError,
6
6
InvalidReturnValueError,
7
- RequestAbortedError
7
+ RequestAbortedError,
8
+ ResponseStatusCodeError
8
9
} = require ( '../core/errors' )
9
10
const util = require ( '../core/util' )
10
11
const { AsyncResource } = require ( 'async_hooks' )
@@ -16,7 +17,7 @@ class StreamHandler extends AsyncResource {
16
17
throw new InvalidArgumentError ( 'invalid opts' )
17
18
}
18
19
19
- const { signal, method, opaque, body, onInfo, responseHeaders } = opts
20
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
20
21
21
22
try {
22
23
if ( typeof callback !== 'function' ) {
@@ -57,6 +58,7 @@ class StreamHandler extends AsyncResource {
57
58
this . trailers = null
58
59
this . body = body
59
60
this . onInfo = onInfo || null
61
+ this . throwOnError = throwOnError || false
60
62
61
63
if ( util . isStream ( body ) ) {
62
64
body . on ( 'error' , ( err ) => {
@@ -76,8 +78,8 @@ class StreamHandler extends AsyncResource {
76
78
this . context = context
77
79
}
78
80
79
- onHeaders ( statusCode , rawHeaders , resume ) {
80
- const { factory, opaque, context } = this
81
+ onHeaders ( statusCode , rawHeaders , resume , statusMessage ) {
82
+ const { factory, opaque, context, callback } = this
81
83
82
84
if ( statusCode < 200 ) {
83
85
if ( this . onInfo ) {
@@ -96,6 +98,32 @@ class StreamHandler extends AsyncResource {
96
98
context
97
99
} )
98
100
101
+ if ( this . throwOnError && statusCode >= 400 ) {
102
+ const headers = this . responseHeaders === 'raw' ? util . parseRawHeaders ( rawHeaders ) : util . parseHeaders ( rawHeaders )
103
+ const chunks = [ ]
104
+ const pt = new PassThrough ( )
105
+ pt
106
+ . on ( 'data' , ( chunk ) => chunks . push ( chunk ) )
107
+ . on ( 'end' , ( ) => {
108
+ const payload = Buffer . concat ( chunks ) . toString ( 'utf8' )
109
+ this . runInAsyncScope (
110
+ callback ,
111
+ null ,
112
+ new ResponseStatusCodeError (
113
+ `Response status code ${ statusCode } ${ statusMessage ? `: ${ statusMessage } ` : '' } ` ,
114
+ statusCode ,
115
+ headers ,
116
+ payload
117
+ )
118
+ )
119
+ } )
120
+ . on ( 'error' , ( err ) => {
121
+ this . onError ( err )
122
+ } )
123
+ this . res = pt
124
+ return
125
+ }
126
+
99
127
if (
100
128
! res ||
101
129
typeof res . write !== 'function' ||
0 commit comments