简体   繁体   中英

Get() with status code 200 caught in the exception

A very simple get(), while status code is 200, how come it gets into the catch block ?

const { promisify } = require('util');
const { get, post, patch, del } = require('https');

//const [ getPm, postPm, patchPm, deletePm ] = [get, post, patch, del].map(promisify);
const getPm = promisify(get);

(async () => {
    try {
        const res = await getPm('https://www.yahoo.com');
        console.log('success !');
    } catch (e) {
        console.log('failure !');
        console.log(e.statusCode);
    }
})();

When i run it, 'failure' is printed out, status is 200, how come ? Any suggestions ?

The issue in this case is the use of util.promisify . Promisify is for standard "node-style" callbacks, which are functions that are called with two arguments (the first argument is an error, the second argument is the result, if successful).

If you check the docs for https.get , you see that this is not a standard node-style callback, it always just gets passed the result body. This is treated as an error by util.promisify , which is why it always rejects.

You would need to write a small new Promise wrapper yourself, rather than using the built-in promisify function, for your snippet to work. I recommend you skip the hassle and use the already-available request-promise module instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM