当前位置:网站首页>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 .

边栏推荐
- 【FPGA教程案例8】基于verilog的分频器设计与实现
- MySQL 45 lecture learning notes (x) force index
- Tar source code analysis Part 10
- CORS is not intended to protect API endpoints - nikofischer
- Design of test cases
- 校园网络问题
- The important role of host reinforcement concept in medical industry
- Research on an endogenous data security interaction protocol oriented to dual platform and dual chain architecture
- Mysql 45讲学习笔记(十)force index
- The number of patent applications in China has again surpassed that of the United States and Japan, ranking first in the world for 11 consecutive years
猜你喜欢

Splicing plain text into JSON strings - easy language method

Responsive - media query

The cloud native programming challenge ended, and Alibaba cloud launched the first white paper on application liveliness technology in the field of cloud native

leetcode825. Age appropriate friends
![[MySQL] introduction, function, creation, view, deletion and modification of database view (with exercises)](/img/03/2b37e63d0d482d5020b7421ac974cb.jpg)
[MySQL] introduction, function, creation, view, deletion and modification of database view (with exercises)
![[Valentine's day] - you can change your love and write down your lover's name](/img/ab/402872ad39f9dc58fd27dd6fc823ef.jpg)
[Valentine's day] - you can change your love and write down your lover's name

The crackdown on Huawei prompted made in China to join forces to fight back, and another enterprise announced to invest 100 billion in R & D

Uniapp applet subcontracting

用于压缩视频感知增强的多目标网络自适应时空融合

Boosting the Performance of Video Compression Artifact Reduction with Reference Frame Proposals and
随机推荐
Tar source code analysis Part 2
Explain in one sentence what social proof is
centos8安装mysql.7 无法开机启动
Master-slave replication principle of MySQL database
Check and display one column in the known table column
Introduction to spark core components
[FPGA tutorial case 8] design and implementation of frequency divider based on Verilog
响应式——媒体查询
Design of test cases
MySQL 45 lecture learning notes (VII) line lock
leetcode825. 适龄的朋友
[GF (q) + LDPC] regular LDPC coding and decoding design and MATLAB simulation based on the GF (q) field of binary graph
JS common time processing functions
The final week, I split
Electronic Association C language level 1 35, bank interest
tars源码分析之1
Shopping malls, storerooms, flat display, user-defined maps can also be played like this!
BasicVSR++: Improving Video Super-Resolutionwith Enhanced Propagation and Alignment
2022年,或許是未來10年經濟最好的一年,2022年你畢業了嗎?畢業後是怎麼計劃的?
MySQL 45 learning notes (XI) how to index string fields