如何在node.js中捕获http客户端请求异常 [英] How to catch http client request exceptions in node.js

查看:491
本文介绍了如何在node.js中捕获http客户端请求异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个node.js应用程序,我想用来检查一个特定的站点是否启动并返回正确的响应代码。我想要能够捕获任何出现的错误,因为域名未解决或请求超时。问题在于这些错误导致Node出现。我是这个整个异步编程方法的新手,所以我不知道在哪里放我的try / catch语句。

I've got a node.js app that I want to use to check if a particular site is up and returning the proper response code. I want to be able to catch any errors that come up as the domain name isn't resolving or the request is timing out. The problem is is that those errors cause Node to crap out. I'm new to this whole asynchronous programming methodology, so I'm not sure where to put my try/catch statements.

我有一个ajax调用去喜欢/ check / site1。服务器端调用尝试进行连接的函数,然后返回statusCode。这是一个非常简单的功能,我已经将每行包装在一个try / catch中,它从不捕获任何东西。这里是:

I have an ajax call that goes to something like /check/site1. Server side that calls a function which attempts to make a connection and then return the statusCode. It's a very simple function, and I've wrapped each line in a try/catch and it never catches anything. Here it is:

function checkSite(url){
    var site = http.createClient(80, url);
    var request = site.request('GET', '/', {'host': url});
    request.end();
    return request;
  }

即使每一行都包含在try / catch中,我仍然会得到像EHOSTUNREACH这样的无效例外。我想要能够捕获那些并返回到ajax调用。

Even with each of those lines wrapped in a try/catch, I will still get uncaught exceptions like EHOSTUNREACH and so on. I want to be able to catch those and return that to the ajax call.

有关下一步尝试的任何建议?

Any recommendations on what to try next?

推荐答案

http.createClient 已被弃用。

是一个使用新的 http.request 处理错误的简单示例:

Here is a quick example of how to handle errors using the new http.request:

var http = require("http");

var options = {
    host : "www.example.com"
};

var request = http.request(options, function(req) {
    ...
});
request.on('error', function(err) {
    // Handle error
});

request.end();

这篇关于如何在node.js中捕获http客户端请求异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆