当前位置:网站首页>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 .
边栏推荐
- Crawler (III) crawling house prices in Tianjin
- Background and current situation of domestic CDN acceleration
- 【GF(q)+LDPC】基于二值图GF(q)域的规则LDPC编译码设计与matlab仿真
- Code rant: from hard coding to configurable, rule engine, low code DSL complexity clock
- 同一个job有两个source就报其中一个数据库找不到,有大佬回答下吗
- 关于IDEA如何设置快捷键集
- [FPGA tutorial case 8] design and implementation of frequency divider based on Verilog
- NLP-文献阅读总结
- Selenium ide plug-in download, installation and use tutorial
- 电脑通过Putty远程连接树莓派
猜你喜欢
Can the out of sequence message complete TCP three handshakes
what the fuck! If you can't grab it, write it yourself. Use code to realize a Bing Dwen Dwen. It's so beautiful ~!
Research on an endogenous data security interaction protocol oriented to dual platform and dual chain architecture
移动适配:vw/vh
NLP-文献阅读总结
A new understanding of how to encrypt industrial computers: host reinforcement application
[thread pool]
Knowledge payment applet dream vending machine V2
Boosting the Performance of Video Compression Artifact Reduction with Reference Frame Proposals and
[MySQL] introduction, function, creation, view, deletion and modification of database view (with exercises)
随机推荐
Introduction to spark core components
CORS is not intended to protect API endpoints - nikofischer
tars源码分析之10
Novel website program source code that can be automatically collected
win10微软拼音输入法输入文字时候下方不出现中文提示
Selection (022) - what is the output of the following code?
How can the old version of commonly used SQL be migrated to the new version?
[MySQL] introduction, function, creation, view, deletion and modification of database view (with exercises)
What is the "relative dilemma" in cognitive fallacy?
ABCD four sequential execution methods, extended application
leetcode825. 适龄的朋友
《剑指Offer》第2版——力扣刷题
[thread pool]
Mobile adaptation: vw/vh
【FPGA教程案例7】基于verilog的计数器设计与实现
kubernetes集群之Label管理
List of top ten professional skills required for data science work
由于dms升级为了新版,我之前的sql在老版本的dms中,这种情况下,如何找回我之前的sql呢?
电子协会 C语言 1级 35 、银行利息
What is a spotlight effect?