Node.js http.createServer如何获取错误 [英] Node.js http.createServer how to get error
问题描述
我是node.js的新手,我正在尝试基本的东西。
I am new to node.js and am trying to experiment with basic stuff.
我的代码是这个
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
这是一个问题 - 如何在调用createServer时看到抛出的异常(或抛出的事件)?我尝试过try / catch但它似乎不起作用。在模块的API中,我找不到任何对它的引用。我问,因为我不小心在一个端口上启动了一个服务器(8888),我得到的错误(在命令行中)是错误:EDDRINUSE,这很有用但是能够理解如何捕获错误会很好在节点中。
Here's the question - how can I see the exceptions thrown (or events thrown) when calling createServer ? I tried try/catch but it doesn't seem to work . In module's API I couldn't find any reference to it . I am asking because I accidentally started a server on a taken port(8888) and the error I got (in command-line) was Error : EDDRINUSE , this is useful enough but it would be nice to be able to understand how errors are caught in node .
推荐答案
您可以通过处理正在创建的服务器上的错误事件来执行此操作。首先,得到 .createServer()
的结果。
You can do this by handling the error event on the server you are creating. First, get the result of .createServer()
.
var server = http.createServer(function(request, response) {
然后,您可以轻松处理错误:
Then, you can easily handle errors:
server.on('error', function (e) {
// Handle your error here
console.log(e);
});
这篇关于Node.js http.createServer如何获取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!