forwardemail / forwardemail/superagent

Getting errors/response status/response text when piping

Open
#1,547 1 comment 4 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
16.6k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

When expecting either a download or an error message as a response, it seems difficult to handle either the one or the other with superagent.

I consulted [this github issue](https://github.com/visionmedia/superagent/issues/565) and [this stack overflow question](https://stackoverflow.com/questions/48545193/catch-superagent-request-error-before-piping) to get this far:

Assuming you have a backend like this (pseudo php code):
```php
$route['/get_download/$1'] = function($downloadFilename) {
if (file_exists($downloadFilename) {
// send the file
readfile($downloadFilename);
} else {
// send text
http_response_code(404);
echo 'We are very sorry!';
}
}
```

This would be the requesting client:
```js
const req = superagent
.get('example.com/get_download/hello.png);

req.on('response', res => {
if (res.status !== 200) {
req.abort();
// res.error.status is available
// no res.error.text, no res.text
console.log('File could not be downloaded. Status: ' + res.error.status + ', reason: ' + res.text);
// should print "File could not be downloaded. Status: 404, reason: We are very sorry!"
}
});

const stream = fs.createWriteStream(download);
req.pipe(stream)
.on('finish', () => {
console.log('File downloaded');
});
```
The downloading part works as expected, but as soon as I get to error handling, it gets messy. Of course this is a simplified example, I am handling a lot of errors/codes with substantial messages.

Is there anything I miss? As `req.on('response')` is not documented (at least not in [this offical documentation](http://visionmedia.github.io/superagent/)) I have the feeling this is not as far in development as I hoped/expected.

**Edit**: just to clarify: I am using `req.on('response')` as a workaround here because `req.on('error')` does not fire, as explained in the referenced issue.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.