简体   繁体   English

异常捕获到状态代码为200的Get()

[英]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 ? 一个非常简单的get(),状态码为200时,它如何进入catch块?

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 ? 当我运行它时,打印出“失败”,状态为200,怎么来的? Any suggestions ? 有什么建议么 ?

The issue in this case is the use of util.promisify . 在这种情况下,问题是使用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). Promisify适用于标准的“节点样式”回调,这是使用两个参数调用的函数(第一个参数是错误,第二个参数是结果(如果成功))。

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. 如果在文档中检查https.get ,您会发现这不是标准的节点样式回调,它始终只是传递给结果正文。 This is treated as an error by util.promisify , which is why it always rejects. util.promisify其视为错误,因此它总是拒绝。

You would need to write a small new Promise wrapper yourself, rather than using the built-in promisify function, for your snippet to work. 您需要自己编写一个小的new Promise包装器,而不是使用内置的promisify函数,以使您的代码片段正常工作。 I recommend you skip the hassle and use the already-available request-promise module instead. 我建议您跳过麻烦,而使用已可用的请求-承诺模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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