如何处理node.js中的代码异常? [英] How to handle code exceptions in node.js?

查看:163
本文介绍了如何处理node.js中的代码异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了Express的文档,描述错误处理的部分完全是

I went through the documentation of Express, and the part describing error handling is completely opaque to me.

我认为他们所指的应用程序是一个实例 createServer(),对吧?但是,在处理请求时发生异常时,我不知道如何阻止node.js引发应用程序进程。

I figured the app they're referring to is an instance createServer(), right? But I have no clue how to stop node.js from blowing up the application process when an exception occurs during handling a request.

我真的不需要任何东西;只要有异常,我只想返回一个500的状态,再加上一个空的响应。节点过程不能终止,因为某处存在未捕获的异常。

I don't need anything fancy really; I just want to return a status of 500, plus an otherwise empty response, whenever there's an exception. The node process must not terminate just because there was an uncaught exception somewhere.

有没有一个简单的例子来实现这个? p>




Is there a simple example of how to achieve this?

var express = require('express');
var http = require('http');

var app = express.createServer();

app.get('/', function(req, res){
    console.log("debug", "calling")
    var options = {
        host: 'www.google.com',
        port: 80,
        path: "/"
    };
    http.get(options, function(response) {
       response.on("data", function(chunk) {
           console.log("data: " + chunk);
           chunk.call(); // no such method; throws here
       });
    }).on('error', function(e) {
       console.log("error connecting" + e.message);
    });
});

app.configure(function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.listen(3000);

崩溃整个应用程序,产生追溯

crashes the entire app, producing traceback

mypath/tst.js:16
           chunk.call(); // no such method; throws here
                 ^ TypeError: Object ... has no method 'call'
    at IncomingMessage.<anonymous> (/Library/WebServer/Documents/discovery/tst.js:16:18)
    at IncomingMessage.emit (events.js:67:17)
    at HTTPParser.onBody (http.js:115:23)
    at Socket.ondata (http.js:1150:24)
    at TCP.onread (net.js:374:27)


推荐答案

如果您真的想捕获所有异常并提供除退出Node.js进程之外的一些处理,则需要处理节点的 uncaughtException 事件。

If you really want to catch all exceptions and provide some handling other than exiting the Node.js process, you need to handle Node's uncaughtException event.

如果您考虑,这是一个Node的东西,而不是Express的东西,因为如果你从一些任意的代码中抛出一个异常,那么Express就不能保证Express可以或者将会看到它,或者可以去捕捉它。 (为什么?异常不是与Node类型的异步事件驱动的callbacky代码进行很好的交互,异常可以从调用堆栈中找到一个 catch()如果 myFunction 在某些事件发生时运行的回调函数将某些工作撤回,则返回到事件循环,然后在该回调时函数被调用,它直接从主事件循环调用,并且 myFunction 不再在调用堆栈上;如果此回调函数抛出异常,即使 myFunction 有一个try / catch块,它不会捕获异常。)

If you think about it, this is a Node thing, and not an Express thing, because if you throw an exception from some arbitrary piece of code, there's no guarantee Express can or will ever see it, or be in a position to trap it. (Why? Exceptions don't interact very well with asynchronous event-driven callbacky code that is the Node style. Exceptions travel up the call stack to find a catch() block that's in scope at the time the exception is thrown. If myFunction defers some work to a callback function that runs when some event happens, then return to the event loop, then when that callback function is invoked, it's invoked directly from the main event loop, and myFunction is no longer on the call stack; if this callback function throws an exception, even if myFunction has a try/catch block, it's not going to catch the exception.)

这在实践中意味着如果你抛出一个异常,不要自己抓住它,并且在Express中直接调用的函数中执行此操作,Express可以捕获异常并调用已安装的错误处理程序,假设您已经配置了一些错误处理中间件喜欢e app.use(express.errorHandler())。但是如果您在响应异步事件时调用的函数中抛出相同的异常,Express将无法捕获它。 (唯一的方法是通过监听全局节点 uncaughtException 事件,这将是一个坏主意,因为这是全局的,你可能需要使用它来进行其他事情,第二是因为Express将不知道与异常相关联的请求。)

What this means in practice is that if you throw an exception and don't catch it yourself and you do so in a function that was directly called by Express, Express can catch the exception and call the error handler you've installed, assuming you've configured some piece of error-handling middleware like app.use(express.errorHandler()). But if you throw the same exception in a function that was called in response to an asynchronous event, Express won't be able to catch it. (The only way it could catch it is by listening for the global Node uncaughtException event, which would be a bad idea first because that's global and you might need to use it for other things, and second because Express will have no idea what request was associated with the exception.)

这是一个例子。我将路由处理代码片段添加到现有的Express应用程序中:

Here's an example. I add this snippet of route-handling code to an existing Express app:

app.get('/fail/sync', function(req, res) {
   throw new Error('whoops');
});
app.get('/fail/async', function(req, res) {
   process.nextTick(function() {
      throw new Error('whoops');
   });
});

现在,如果我访问 http:// localhost:3000 / fail / sync 在浏览器中,浏览器会转储一个调用堆栈(显示express.errorHandler的操作)。但是,如果浏览器中访问 http:// localhost:3000 / fail / async ,浏览器会生气(Chrome显示没有收到数据:错误324,网络:: ERR_EMPTY_RESPONSE:服务器关闭连接而不发送任何数据消息),因为节点进程已经退出,在我调用的终端上的stdout上显示一个回溯。

Now if I visit http://localhost:3000/fail/sync in my browser, the browser dumps a call stack (showing express.errorHandler in action). If I visit http://localhost:3000/fail/async in my browser, however, the browser gets angry (Chrome shows a "No data received: Error 324, net::ERR_EMPTY_RESPONSE: The server closed the connection without sending any data" message), because the Node process has exited, showing a backtrace on stdout in the terminal where I invoked it.

这篇关于如何处理node.js中的代码异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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