How to solve uncaught exceptions in Node.js
Uncaught Exceptions in Node.js
Handling Uncaught Exceptions in Node.js is not very easy
Directory:
Problems caused by uncaught exceptions
How to deal with uncaught exceptions
An application without uncaught exceptions
Crash your application
Pretend you don’t see the error?
The application crashes, prints the log, and then restarts
Use the Domains module [Translator's Note: Now obsolete]
Conclusion
1. Problems caused by uncaught exceptions
Due to the single-threaded nature of Node.js, uncaught exceptions are a problem for application development Issues worth noting during the process. Node.js follows a callback pattern of errors first, data second. We often see this example: when the callback function returns an error object, the error is thrown immediately.
var fs = require('fs'); fs.readFile('somefile.txt', function (err, data) { if (err) throw err; console.log(data); });
If you run this program, and assuming you don't have the file somefile.txt
, an error will be thrown.
Error: ENOENT, open 'somefile.txt'
This will cause the process to crash and affect the entire APP.
This is intentional, Node.js does not intend to separate your application and service.
2. How to handle uncaught exceptions
What is the best way to handle uncaught exceptions? There are so many ways:
Your application should not have uncaught errors, it's crazy.
It's also crazy that you should let your app find uncaught exceptions after a crash and then fix them.
Turning a blind eye to a mistake and not dealing with it—that’s what most people do, and it sucks.
You should let your application print out the error log after a crash, and then use
upstart
,forever
,monit
Something like this restarts the process. This method is very practical.[Translator's Note: Now obsolete] You should start using the Domains module to handle errors. This is the only way to go, although this is still an experimental feature of Node.js.
Now let’s expand these methods in detail.
3. An application without uncaught exceptions
The concept of "an application without uncaught exceptions" is weird to me, any application will have exceptions at some point and it may be Uncaught exception. If you insist on this point and throw errors to users, then I think you should be prepared to get a phone call in the middle of the night and be told that the service has crashed.
4. Crash your application
The only defence I can find in this opinion is the fail fast argument. You are going to fix your application quickly if it unavailable. If an application without uncaught exceptions is letting denial your application crash is acceptance. But you are still pushing exception handling onto your users. (Forgive me for not being able to figure out how to translate this paragraph. If you have good ideas, please contact me as soon as possible!)
5. Pretend not to see the error?
Many people do this:
<p style="margin-bottom: 7px;">process.on('uncaughtException', function (err) {<br/> console.log(err);<br/>})<br/></p>
This is bad. When an uncaught exception is thrown, you should realize that your application is in an abnormal state. In this case You can't run your program reliably.
Felix Geisendörfer
who originally proposed the process.on event now advocates its removal.
6. The application crashes, prints the log, and then restarts
With this method you can make your application crash immediately when an uncaught exception occurs, and then use forever
or upstart
Such a tool can restart (almost) instantly. Node.js will write the exception to STERR
so you can redirect the exception to a log file and get the error from it later. The disadvantage of this approach is that it does not provide an elegant way to handle temporary power outages or network errors if the error occurs outside of your code. scene. What a tool! — Restart the app and try again. If you combine this strategy with cluster module
, node can automatically restart any children that throw an error and print out the error. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>var cluster = require(&#39;cluster&#39;);var workers = process.env.WORKERS || require(&#39;os&#39;).cpus().length;if (cluster.isMaster) {
console.log(&#39;start cluster with %s workers&#39;, workers); for (var i = 0; i < workers; ++i) { var worker = cluster.fork().process;
console.log(&#39;worker %s started.&#39;, worker.pid);
}
cluster.on(&#39;exit&#39;, function(worker) {
console.log(&#39;worker %s died. restart...&#39;, worker.process.pid);
cluster.fork();
});
} else { var http = require(&#39;http&#39;);
http.createServer(function (req, res) {
res.end("Look Mum! I&#39;m a server!\n");
}).listen(3000, "127.0.0.1");
}
process.on(&#39;uncaughtException&#39;, function (err) {
console.error((new Date).toUTCString() + &#39; uncaughtException:&#39;, err.message)
console.error(err.stack)
process.exit(1)
})</pre><div class="contentsignin">Copy after login</div></div>
7. Use the Domains
module [Translator’s Note: Now obsolete]
Domains
is
Node.js v0.8 An experimental feature added in the version, which makes exception handling more flexible and precise. The following is an example where the file does not exist. By using domains
, you can trigger an error event for a specific domain. You can also use different exception handling for different scenarios. This allows you to handle exceptions accordingly based on where they occur. If exiting a process is like cracking a nut with a hammer, this is like a precise scalpel giving you complete control over the program. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>var domain = require(&#39;domain&#39;);var d = domain.create();var fs = require(&#39;fs&#39;);
d.on(&#39;error&#39;, function(err) {
console.error(err);
});
d.run(function() {
fs.readFile(&#39;somefile.txt&#39;, function (err, data) {
if (err) throw err;
console.log(data);
});
});</pre><div class="contentsignin">Copy after login</div></div><h3 id="结论">8. 结论</h3>
<p>如果你在产品环境运行 Node.js 你起码应该对如何处理异常有一个想法。目前为止我相信当异常被抛出时,大多数人只是重启应用(也许是优雅地重启),<code>Domains
为应用提供了一种更聪明的面对异常的能力,异常处理器可能会选择简单的清理、关闭某些连接,最坏的情况下,退出进程。关键点就在于你有了选择。
我抛下榔头拾起手术刀的时候应该已经到了
The above is the detailed content of How to solve uncaught exceptions in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to set up keyboard startup on Gigabyte's motherboard. First, if it needs to support keyboard startup, it must be a PS2 keyboard! ! The setting steps are as follows: Step 1: Press Del or F2 to enter the BIOS after booting, and go to the Advanced (Advanced) mode of the BIOS. Ordinary motherboards enter the EZ (Easy) mode of the motherboard by default. You need to press F7 to switch to the Advanced mode. ROG series motherboards enter the BIOS by default. Advanced mode (we use Simplified Chinese to demonstrate) Step 2: Select to - [Advanced] - [Advanced Power Management (APM)] Step 3: Find the option [Wake up by PS2 keyboard] Step 4: This option The default is Disabled. After pulling down, you can see three different setting options, namely press [space bar] to turn on the computer, press group

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to enable the direct connection of the independent graphics card of the Shenzhou Xuanlong m7. To enable the direct connection function of the independent graphics card of the Shenzhou Xuanlong m7, you can follow the following steps: 1. First, make sure that you have installed the driver of the independent graphics card. You can go to the official Shenzhou website or the official website of the independent graphics card manufacturer to download and install the latest driver suitable for your graphics card model. 2. On the computer desktop, right-click a blank space and select "NVIDIA Control Panel" in the pop-up menu (if it is an AMD graphics card, select "AMDRadeon Settings"). 3. In the control panel, find "3D Settings" or a similarly named option and click to enter. 4. In "3D Settings" you need to find "Global Settings" or a similarly named option. Here you can specify the use of a unique

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

As a world-renowned sports brand, Nike's shoes have attracted much attention. However, there are also a large number of counterfeit products on the market, including fake Nike shoe boxes. Distinguishing genuine shoe boxes from fake ones is crucial to protecting the rights and interests of consumers. This article will provide you with some simple and effective methods to help you distinguish between real and fake shoe boxes. 1: Outer packaging title By observing the outer packaging of Nike shoe boxes, you can find many subtle differences. Genuine Nike shoe boxes usually have high-quality paper materials that are smooth to the touch and have no obvious pungent smell. The fonts and logos on authentic shoe boxes are usually clear and detailed, and there are no blurs or color inconsistencies. 2: LOGO hot stamping title. The LOGO on Nike shoe boxes is usually hot stamping. The hot stamping part on the genuine shoe box will show

What is the resolution of Savior Y7000P when playing CF? The resolution of Savior Y7000P when playing CF is 1920*1080. Because this computer is equipped with a GTX1650 graphics card and an i5-9300H processor, its performance is relatively good and sufficient to meet the needs of games such as CF. At the same time, 1920*1080 is the current resolution of mainstream e-sports monitors, and the image quality and clarity are sufficient. In addition, if there are players with higher requirements, you can appropriately lower the game image quality settings to obtain a smoother gaming experience. In order to enjoy a clearer visual experience, you can adjust the resolution of the Savior y7000p to 2560*1400. This way, you will be able to enjoy higher quality image display. Equipped with the Savior Y7000P 2022 model
