繁体   English   中英

Node.js https.get.on(“错误”,函数(e){…}不起作用

[英]Node.js https.get.on(“error”, function(e){…} Not working

虽然试图完成一个Node.js的课程上Treehouse.com我无法得到的.on("error")的处理https.get()工作。 下面是我的代码:

var https = require("https");

// Print out message
function printMessage(username, badgeCount, points) {
  var message = username + " has " + badgeCount + " total badge(s) and " + points + " points in JavaScript.";
  console.log(message);
}

// Print out error messages
function printError(error) {
  console.error(error.message);
}

function get(username) {
  // Connect to the API URL (https://teamtreehouse/username.json)
  var request = https.get("teamtreehouse.com/" + username + ".json", function(response){
    var body = "";
    // Read the data
    response.on("data", function (chunk) {
      body += chunk;
    });
    response.on("end", function(){
      if (response.statusCode === 200) {
        try {
          // Parse the data
          var profile = JSON.parse(body);
          // Print the data
          printMessage(username, profile.badges.length, profile.points.JavaScript);
        } catch (error) {
          // Parse Error
          printError(error);
        }
      } else {
        // Status Error
        printError({message: "The user: " + username + " can not be found. HTTP Status Code: " + response.statusCode});

      }
    });
  });
  // Connection error
  request.on("error", printError);
}

module.exports.get = get;

URL中的协议已被有意删除,从而导致连接错误。 应该由request.on("error", printError); 但是事实并非如此。 相反,控制台中的反馈是:

https.js:191
      throw new Error('Unable to determine the domain name');
      ^

Error: Unable to determine the domain name
    at Object.exports.request (https.js:191:13)
    at Object.exports.get (https.js:201:21)
    at get (/Users/dangranger/Sites/sandbox/JavaScript/Node/profile.js:16:23)
    at Array.forEach (native)
    at Object.<anonymous> (/Users/dangranger/Sites/sandbox/JavaScript/Node/treehouseApp.js:3:7)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)

我正在使用Node.js 5.6.0

感谢@adeneo,看来您是对的。 似乎要捕获这种错误,您需要一个try catch块,如本答案中所述, 为什么这种基本的Node.js错误处理无法正常工作?

暂无
暂无

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

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