简体   繁体   English

Node.js http.createServer如何获取错误

[英]Node.js http.createServer how to get error

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 ? 这是一个问题 - 如何在调用createServer时看到抛出的异常(或抛出的事件)? I tried try/catch but it doesn't seem to work . 我尝试过try / catch但它似乎不起作用。 In module's API I couldn't find any reference to it . 在模块的API中,我找不到任何对它的引用。 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 . 我问,因为我不小心在一个端口上启动了一个服务器(8888),我得到的错误(在命令行中)是错误:EDDRINUSE,这很有用但是能够理解如何捕获错误会很好在节点中。

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);
});

Print stacktrace of uncaught exceptions using following code. 使用以下代码打印未捕获异常的堆栈跟踪。

process.on('uncaughtException', function( err ) {
            console.error(err.stack);
 });

The error is emitted in the listen() method. 该错误在listen()方法中发出。 The API documentation includes an example just for your situtation. API文档包含一个仅供您参与的示例

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服务器的任何未处理的异常都可能像这样被捕获。

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

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