javascript Node.js http.createServer 如何获取错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12496491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js http.createServer how to get error
提问by user1551120
I am new to node.js and am trying to experiment with basic stuff.
我是 node.js 的新手,正在尝试尝试基本的东西。
My code is this
我的代码是这样的
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
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 时如何查看抛出的异常(或抛出的事件)?我试过 try/catch 但它似乎不起作用。在模块的 API 中,我找不到任何对它的引用。我问是因为我不小心在一个被占用的端口(8888)上启动了一个服务器,我得到的错误(在命令行中)是 Error : EDDRINUSE ,这足够有用,但能够理解错误是如何被捕获的会很好在节点。
回答by Brad
You can do this by handling the error event on the server you are creating. First, get the result of .createServer()
.
您可以通过处理您正在创建的服务器上的错误事件来做到这一点。首先,得到 的结果.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);
});
回答by Anoop
Print stacktrace of uncaught exceptions using following code.
使用以下代码打印未捕获异常的堆栈跟踪。
process.on('uncaughtException', function( err ) {
console.error(err.stack);
});
回答by Martin
The error is emitted in the listen() method. The API documentationincludes an examplejust for your situtation.
回答by J?rgen
You can use
您可以使用
process.on('uncaughtException', function(e){
console.log(e);
});
To handle uncaught exceptions. Any unhandled exception from the web server could be caught like this.
处理未捕获的异常。来自 Web 服务器的任何未处理的异常都可以像这样被捕获。