It's sometime useful to make an http and only verify the statusCode. For example to check is a resource is available (check statusCode === 404) or authorized (check statusCode === 401).
Current that requires to handle the error with a try / catch:
async function isAuthorized(url) {
try {
const response = await got(url);
return response.statusCode !== 401;
} catch (err) {
if (err.statusCode) {
return err.statusCode !== 401;
}
throw err;
}
}
The reject option would work similarly to execa#reject. In case of a 4xx error the error would be returned instead of being thrown. Other error cases (5xx, network, timeout etc...) would throw the error.
The code above would look like this:
async function isAuthorized(url) {
return (await got(url, {reject: false})).statusCode !== 401;
}
I'm lukewarm to the idea. It does simplify the above code, but it doesn't look like something you would commonly do. I'm gonna see what the other team members think.
It's a tricky one, if you're expecting non 200 responses it is currently kind of awkward to handle. But returning the error could cause some serious confusion if you end up accidentally passing an error to code that's expecting a response object and vice versa. The only way to cater for that would be to check whether you've got a response or error first, but then that's not much cleaner than try/catch.
One alternative solution could be to have an option to not throw on bad HTTP response codes at all, just return the response and let the user handle the status code. That seems like a more generic solution that would be helpful for more use cases.
Something like:
await got('/500-error');
// throws Error
await got('/500-error', {throwHttpErrors: false});
// returns response object with 500 status code
await got('/network-error', {throwHttpErrors: false});
// throws Error
Let's go with @lukechilds' proposal.
Most helpful comment
It's a tricky one, if you're expecting non 200 responses it is currently kind of awkward to handle. But returning the error could cause some serious confusion if you end up accidentally passing an error to code that's expecting a response object and vice versa. The only way to cater for that would be to check whether you've got a response or error first, but then that's not much cleaner than try/catch.
One alternative solution could be to have an option to not throw on bad HTTP response codes at all, just return the response and let the user handle the status code. That seems like a more generic solution that would be helpful for more use cases.
Something like: