当前位置:网站首页>Solution of running crash caused by node error
Solution of running crash caused by node error
2022-07-04 07:01:00 【Brother Lei talks about programming】
Many people have such an image ,NodeJS Faster ; But because it's single threaded , So it's unstable , It's not safe , Not suitable for complex business ; It's more suitable for high concurrency requirements , And simple business scenarios .
stay Express The author of TJ Holowaychuk Of a farewell Node.js The following counts are listed in the article :
Farewell NodeJS (TJ Holowaychuk)
• you may get duplicate callbacks
• you may not get a callback at all (lost in limbo)
• you may get out-of-band errors
• emitters may get multiple “error” events
• missing “error” events sends everything to hell
• often unsure what requires “error” handlers
• “error” handlers are very verbose
• callbacks suck
In fact, these points mainly make two noises : node.js Error handling is bullshit ,node.js The callback of is also bullshit .
In fact? ?
in fact NodeJS Mileage does exist “ fragile ” One side , Somewhere in a single thread “ Unprocessed ” Exceptions do cause the whole Node.JS Crash exit , Take an example , Here's one node-error.js The file of :
var http = require('http');
var server = http.createServer(function (req, res) {
// There's a mistake here ,params yes undefined
var ok = req.params.ok;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
Start the service , And test it in the address bar and find http://127.0.0.1:8080/ It is as expected ,node collapsed
$ node node-error
Server running at http://127.0.0.1:8080/
c:\github\script\node-error.js:5
var ok = req.params.ok;
^
TypeError: Cannot read property 'ok' of undefined
at Server.<anonymous> (c:\github\script\node-error.js:5:22)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:525:27)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
How to solve it ?
Actually Node.JS To this day , If you can't even solve this problem , It is estimated that no one has used it for a long time .
Use uncaughtException
We can uncaughtException To capture the UN captured data globally Error, At the same time, you can print out the call stack of this function , After capture, it can effectively prevent node Process exits , Such as :
process.on('uncaughtException', function (err) {
// Print out the error
console.log(err);
// Print out the wrong call stack for debugging
console.log(err.stack);
});
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
This is equivalent to node Guard inside the process , But this method is not advocated by many people , It means that you can't fully control Node.JS It's abnormal .
Use try/catch
We can also add try/catch, Also ensure thread safety .
var http = require('http');
http.createServer(function(req, res) {
try {
handler(req, res);
} catch(e) {
console.log('\r\n', e, '\r\n', e.stack);
try {
res.end(e.stack);
} catch(e) { }
}
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');
var handler = function (req, res) {
//Error Popuped
var name = req.params.name;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello ' + name);
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
The advantage of this scheme is , You can output the error and call stack directly to the current web page .
Integrate into the framework
The standard HTTP Response processing goes through a series of Middleware(HttpModule), Finally arrive at Handler, As shown in the figure below :
this some Middleware and Handler stay NodeJS There is a feature in , They're all callback functions , The callback function is the only one that makes Node Where the runtime crashes . According to this characteristic , We only need to integrate one place in the framework try/catch It can solve abnormal problems relatively perfectly , And it will not affect the requests of other users request.
As a matter of fact, now NodeJS WEB Almost all frameworks do this , Such as OurJS Open source blog Based on the WebSvr
There is such an exception handling code :
try {
handler(req, res);
} catch(err) {
var errorMsg
= '\n'
+ 'Error ' + new Date().toISOString() + ' ' + req.url
+ '\n'
+ err.stack || err.message || 'unknow error'
+ '\n'
;
console.error(errorMsg);
Settings.showError
? res.end('<pre>' + errorMsg + '</pre>')
: res.end();
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 1.
So what about the errors not generated in the callback ? Don't worry about , In fact, this is node The program doesn't work at all .
Besides node Self contained cluster It also has certain fault tolerance , It goes with nginx Of worker Is very similar , But it consumes resources ( Memory ) Slightly larger , Programming is not very convenient ,OurJS This design is not adopted .
guardian NodeJS Process and log errors
present It has been basically solved Node.JS The problem of collapse due to abnormality , But no platform is 100% reliable , There are also some mistakes from Node Thrown by the bottom , There's something unusual try/catch and uncaughtException Can't capture . It was running before ourjs When , Occasionally, I will encounter the file stream reading exception thrown by the bottom , This is a bottom layer libuv Of BUG,node.js stay 0.10.21 It's been fixed in .
In the face of this situation , We should work for nodejs Apply add daemon , Give Way NodeJS It can be revived immediately after encountering abnormal collapse .
in addition , These generated exceptions should also be recorded in the log , And let the exception never happen again .
Use node To guard node
node-forever It provides guard functions and LOG Logging function .
Installation is very easy
[sudo] npm install forever
- 1.
It's also easy to use
$ forever start simple-server.js
$ forever list
[0] simple-server.js [ 24597, 24596 ]
- 1.
- 2.
- 3.
You can also read the log
forever -o out.log -e err.log my-script.js
- 1.
Use shell Start script daemon node
Use node To guard, the resource cost may be a little high , And it will be slightly complicated ,OurJS Start the script directly at startup to guard the process thread .
If in debian Placed in ourjs Boot file : /etc/init.d/ourjs
This file is very simple , Only startup options , The core function of guard is an infinite loop while true; To achieve , In order to prevent too dense error blocking process , Interval after each error 1 Restart the service in seconds
WEB_DIR='/var/www/ourjs'
WEB_APP='svr/ourjs.js'
#location of node you want to use
NODE_EXE=/root/local/bin/node
while true; do
{
$NODE_EXE $WEB_DIR/$WEB_APP config.magazine.js
echo "Stopped unexpected, restarting \r\n\r\n"
} 2>> $WEB_DIR/error.log
sleep 1
done
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
Error logging is also very simple , Directly output the errors in this process console to error.log File can : 2>> $WEB_DIR/error.log This business , 2 representative Error.
Follow the QR code below , Subscribe to more .

边栏推荐
- Mysql 45讲学习笔记(七)行锁
- The cloud native programming challenge ended, and Alibaba cloud launched the first white paper on application liveliness technology in the field of cloud native
- Cochez une colonne d'affichage dans une colonne de tableau connue
- Deep profile data leakage prevention scheme
- MySQL relearn 2- Alibaba cloud server CentOS installation mysql8.0
- [Valentine's day] - you can change your love and write down your lover's name
- 高薪程序员&面试题精讲系列119之Redis如何实现分布式锁?
- 测试用例的设计
- Tar source code analysis Part 7
- What is industrial computer encryption and how to do it
猜你喜欢

How notepad++ counts words

Recursive Fusion and Deformable Spatiotemporal Attention for Video Compression Artifact Reduction

Selenium ide plug-in download, installation and use tutorial

selenium驱动IE常见问题解决Message: Currently focused window has been closed.

What is industrial computer encryption and how to do it

selenium IDE插件下载安装使用教程

Introduction to spark core components

期末周,我裂开

2022 where to find enterprise e-mail and which is the security of enterprise e-mail system?

centos8安装mysql.7 无法开机启动
随机推荐
Tar source code analysis 9
Redis interview question set
Uniapp applet subcontracting
[GF (q) + LDPC] regular LDPC coding and decoding design and MATLAB simulation based on the GF (q) field of binary graph
Recursive Fusion and Deformable Spatiotemporal Attention for Video Compression Artifact Reduction
[thread pool]
tars源码分析之2
抽奖系统测试报告
What is the "relative dilemma" in cognitive fallacy?
com. alibaba. nacos. api. exception. NacosException
What is Gibson's law?
响应式移动Web测试题
Wechat applet scroll view component scrollable view area
《剑指Offer》第2版——力扣刷题
【FPGA教程案例7】基于verilog的计数器设计与实现
请问旧版的的常用SQL怎么迁移到新版本里来?
Latex中的单引号,双引号如何输入?
Mysql 45讲学习笔记(十三)表数据删掉一半,表文件大小不变
Why does the producer / consumer mode wait () use while instead of if (clear and understandable)
MySQL 45 lecture learning notes (VI) global lock