---
title: "nodejs process uncaughtException"
author: "qson"
date: "2014-04-03T09:41:52Z"
tags: []
categories: ["编程语言"]
slug: "nodejs-process-uncaughtexception"
draft: false
lastmod: "2014-04-03T09:46:27Z"
id: 2040329
url: "https://qson.iteye.com/blog/2040329"
---

用过Node一段时间之后，发现那些在事件主循环里碰到的异常会导致Node进程退出。在许多应用场景下，特别是对那些希望永不当机的服务器程序来说，这都是不接受的。**uncaughtException**事件会提供一个极其暴力的方法来捕获这些异常。它确实是最后一道防线了，但对解决此问题上非常有效果。
**示例1**

```js

var http = require('http');

var server = http.createServer(function(req,res){
    res.writeHead(200,{});
    res.end('response');
    setTimeout(function(){
        console.log('This will still run.');
    },2000);
    method(); //由于method()未定义，会将程序进程退出。
    console.log('response end');
});

server.listen(10086);

process.on('uncaughtException', function (err) {
    console.log('Caught Exception:' + err);//直接捕获method()未定义函数，Node进程未被退出。
});


```

**示例2**

```js

var http = require('http');

var server = http.createServer(function(req,res){
    res.writeHead(200,{});
    res.end('response');
    setTimeout(function(){
        method(); //由于method()未定义，会将程序进程退出。
        console.log('This will still run.');
    },2000);
//    method();
});

server.listen(10086);

process.on('uncaughtException', function (err) {
    console.log('Caught Exception:' + err); //直接捕获method()未定义函数，Node进程未被退出。
});

```


上述的例子，我们为**uncaughtException**创建了一个事件监听器。然后将异常描述做一个简单的标准输出，由于method()函数未定义，所以它捕获了一个不存在的函数触发的事件，所以Node程序程序不会退出，但是标准的执行流程会被打断。**console.log('response end')**这段代码将不会被执行，而**setTimeout()**函数里的程序将在2秒后执行，因为它在异常捕获时，已经加入事件队列中。