Skip to content

Commit a186d20

Browse files
committed
Document workaround for reading HTTP error bodies in streams
Fixes #1898
1 parent 4206f0e commit a186d20

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

documentation/3-streams.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,28 @@ readStream.on('response', async response => {
215215
readStream.once('error', onError);
216216
```
217217

218+
**Example: Reading HTTP error response bodies**
219+
220+
By default, Got throws HTTP errors before the stream becomes readable. To read error response bodies:
221+
222+
```js
223+
import {pipeline as streamPipeline} from 'node:stream/promises';
224+
import got from 'got';
225+
226+
const stream = got.stream('https://httpbin.org/status/404', {
227+
throwHttpErrors: false
228+
});
229+
230+
stream.on('response', response => {
231+
if (!response.ok) {
232+
console.log(`HTTP Error: ${response.statusCode}`);
233+
// Stream is readable, you can pipe or read the error body
234+
}
235+
});
236+
237+
await streamPipeline(stream, process.stdout);
238+
```
239+
218240
**Example: Filter headers when proxying to ServerResponse**
219241

220242
```js
@@ -267,6 +289,7 @@ When this event is emitted, you should reset the stream you were writing to and
267289
> - [`HTTPError`s](./8-errors.md#httperror) cannot be retried if [`options.throwHttpErrors`](./2-options.md#throwhttperrors) is `false`.
268290
> This is because stream data is saved to `error.response.body` and streams can be read only once.
269291
> - For the Promise API, there is no such limitation.
292+
> - If you need to read HTTP error response bodies without retry, see [Reading HTTP error response bodies](#example-reading-http-error-response-bodies).
270293
271294
#### `retryCount`
272295

@@ -402,6 +425,7 @@ Whether the response was successful
402425
> - When [following redirects](2-options.md#followredirect), a request is successful **only** when the status code of the final request is `2xx`.
403426
> - `304` responses are always considered successful.
404427
> - Got throws automatically when `response.ok` is `false` and `throwHttpErrors` is `true`.
428+
> - **To read HTTP error response bodies with streams**, set `throwHttpErrors: false` and check `response.ok` in the `response` event handler. [See example above](#example-reading-http-error-response-bodies).
405429
406430
### `statusCode`
407431

0 commit comments

Comments
 (0)