异常处理

显示异常处理

1
2
3
4
5
6
7
8
9
10
11
12
function fn( name ) {
if( !name ) {
throw new Error("name is required!");
}
}

//显示异常用try/catch处理
try {
fn();
} catch( err ) {
console && console.error( err.message, err.stack );
}

ps:

  1. throw只能用于同步方法中。或者当异步方法中异步执行触发前 throw会生效。
  2. 通常抛出的异常都需要继承于Error。使用简单的字符串(new “ error”)无法获取对应的调用栈,无法获取那里发生错误的相关信息。
  3. 不要在内置的node.js方法中的回调函数中抛出异常;这样捕获到的堆栈没什么有用的信息。我们可以直接处理异常,或把异常交给合适的错误处理函数。

隐藏是异常

1
2
3
function fn(data) {
console.log(date); //ReferenceError: date is not defined
}

try/catch 包住是很有必要的。 例如用try/catch包住JSON.parse也很有必要。

错误事件处理

1
2
3
var EventEmitter = require("events").EventEmitter;
var e = new EventEmitter();
e.emit("error", new Error("no handle to catch me"));

处理方法

1
2
3
e.on("error", function(err) {
console && console.error(err.message, err.stack);
})

参数错误处理

1
2
3
4
5
fs.readFile("./file.txt", function(err, buf) {
if(err) {
return handleError(err);
}
});

处理未捕获的异常

1
2
3
4
5
6
7
8
9
10
var http = require("http");
var server = http.createServer(req, res) {
response.end("hello world");
};
server.listen(3000);
process.on("uncaughtException", function(err){
console && console.error(err);
server.close();
setTimeout(process.exit, 500, 1);
});

使用域来处理未捕获的异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var domain = require("domain");
var http = require("http");

var d = domain.create();
d.run(function() {
var server = http.createServer(req, res) {
d.on("error", function(err) {
res.statusCode = 500;
res.end("internal server error");
setTimeout(process.exit, 5000, 1);
});
response.end("hello world");
};
server.listen(3000);
});

node.js 的问题调试

node debug

1
2
3
// test.js
var a = 123;
console.log(a);

node debug test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
➜  Desktop node debug test.js  
(node:78403) [DEP0068] DeprecationWarning: `node debug` is deprecated. Please use `node inspect` instead.
< Debugger listening on ws://127.0.0.1:9229/eaab7bad-ccd1-46d8-9e82-d5845e864dd7
< For help see https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in test.js:1
> 1 (function (exports, require, module, __filename, __dirname) { var a = 123;
2 console.log(a);
3
debug> help
run, restart, r Run the application or reconnect
kill Kill a running application or disconnect

cont, c Resume execution
next, n Continue to next line in current file
step, s Step into, potentially entering a function
out, o Step out, leaving the current function
backtrace, bt Print the current backtrace
list Print the source around the current line where execution
is currently paused

setBreakpoint, sb Set a breakpoint
clearBreakpoint, cb Clear a breakpoint
breakpoints List all known breakpoints
breakOnException Pause execution whenever an exception is thrown
breakOnUncaught Pause execution whenever an exception isn't caught
breakOnNone Don't pause on exceptions (this is the default)

watch(expr) Start watching the given expression
unwatch(expr) Stop watching an expression
watchers Print all watched expressions and their current values

exec(expr) Evaluate the expression and print the value
repl Enter a debug repl that works like exec

scripts List application scripts that are currently loaded
scripts(true) List all scripts (including node-internals)

profile Start CPU profiling session.
profileEnd Stop current CPU profiling session.
profiles Array of completed CPU profiling sessions.
profiles[n].save(filepath = 'node.cpuprofile')
Save CPU profiling session to disk as JSON.

takeHeapSnapshot(filepath = 'node.heapsnapshot')
Take a heap snapshot and save to disk as JSON.
debug>

ps: 如上方法已不推荐使用。

node inspect test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
➜  Desktop node inspect test.js
< Debugger listening on ws://127.0.0.1:9229/e0ac6cc0-d7db-40ec-bd58-4d9a98f2a18f
< For help see https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in test.js:1
> 1 (function (exports, require, module, __filename, __dirname) { var a = 123;
2 console.log(a);
3
debug> help
run, restart, r Run the application or reconnect
kill Kill a running application or disconnect

cont, c Resume execution
next, n Continue to next line in current file
step, s Step into, potentially entering a function
out, o Step out, leaving the current function
backtrace, bt Print the current backtrace
list Print the source around the current line where execution
is currently paused

setBreakpoint, sb Set a breakpoint
clearBreakpoint, cb Clear a breakpoint
breakpoints List all known breakpoints
breakOnException Pause execution whenever an exception is thrown
breakOnUncaught Pause execution whenever an exception isn't caught
breakOnNone Don't pause on exceptions (this is the default)

watch(expr) Start watching the given expression
unwatch(expr) Stop watching an expression
watchers Print all watched expressions and their current values

exec(expr) Evaluate the expression and print the value
repl Enter a debug repl that works like exec

scripts List application scripts that are currently loaded
scripts(true) List all scripts (including node-internals)

profile Start CPU profiling session.
profileEnd Stop current CPU profiling session.
profiles Array of completed CPU profiling sessions.
profiles[n].save(filepath = 'node.cpuprofile')
Save CPU profiling session to disk as JSON.

takeHeapSnapshot(filepath = 'node.heapsnapshot')
Take a heap snapshot and save to disk as JSON.
debug>

感兴趣,自己尝试了。官方的推荐,但不够可视化。

使用Node inspector

使用node-inspector

$ npm install node-inspector -g

然后需要通过浏览器连接到node-inspector,需要启动inspector服务:

$ node-inspector
最后以debug模式运行node.js应用:

官文使用方法: 实际已不推荐。
$ node --debug app.js

ps: The node-debug command will load Node Inspector in your default browser.

NOTE: Node Inspector works in Chrome and Opera only. You have to re-open the inspector page in one of those browsers if another browser is your default web browser (e.g. Safari or Internet Explorer).

建议使用Chrome为浏览器

实际使用:
$ node --inspect app.js
通过URL http://127.0.0.1:8080/debug?port=5858 就可以进行调试了。

1
2
3
4

#### 两个 node.js 服务自动重启工具推荐

[supervisor](https://www.npmjs.com/package/supervisor)

npm install -g supervisor

//使用
supervisor ./app.js

1
2

[nodemon](https://www.npmjs.com/package/nodemon)

npm install -g nodemon

//使用
nodemon ./app.js
`