Why does this basic Node.js error handling not work?

Node.js

var https = require("https"); var request = https.get("google.com/", function(response) { console.log(response.statusCode); }); request.on("error", function(error) { console.log(error.message); }); 

If I add https: // to the google domain name, then I will get a status code of 200, as expected. As it was, I expect the error to be detected and an error message like "connect ECONNREFUSED" will be printed on the terminal console. Instead, it pushes the stack to the terminal.

+5
source share
1 answer

If you look at the source for https.get() , you will see that if the parsing of the URL fails (what will happen when you just pass it to "google.com/" , since this is not a valid URL), then he simultaneously throws:

 exports.get = function(options, cb) { var req = exports.request(options, cb); req.end(); return req; }; exports.request = function(options, cb) { if (typeof options === 'string') { options = url.parse(options); if (!options.hostname) { throw new Error('Unable to determine the domain name'); } } else { options = util._extend({}, options); } options._defaultAgent = globalAgent; return http.request(options, cb); }; 

So, if you want to catch this type of error, you need to try / catch your https.get() call like this:

 var https = require("https"); try { var request = https.get("google.com/", function(response) { console.log(response.statusCode); }).on("error", function(error) { console.log(error.message); }); } catch(e) { console.log(e); } 
+9
source

Source: https://habr.com/ru/post/1241166/


All Articles