Nodejs Exception Handling Uncaughtexception article
Wang Yu-april 08, 2015
Many NodeJS developers complain about the trouble of handling the exception, and we'll comb through some of the columns to sort out the usual exception handling methods in NodeJS.
As with most programming languages, you can throw
throw an exception in NodeJS:
throw new Error(‘Catch me‘);
In order to catch this exception it is necessary to package the code in Try Catch
:
try{
throw new Error(‘Catch me‘);
}catch(e){
// error captured
}
However, because of the asynchronous nature of the NodeJS, the code above can be invalidated with a little modification:
try{
process.nextTick(function my_app(){
throw new Error(‘Catch me‘);
})
}catch(e){
// never called
}
In the real world, exceptions are always generated in a module. The so-called module is a unit that can complete a function, even a simple function can be seen as a module. As the number of lines of project code increases, the complexity of asynchronous nesting increases, often with exceptions that are not captured. A NodeJS application that has no strong robustness will be suspended because of an uncaught exception, resulting in service unavailability. To change the perception that Nodejs is fragile, developers need to deepen their understanding of the language exception handling mechanism.
Uncaughtexception
uncaughtException
is actually an event of the NodeJS process. This event is triggered if an exception is generated in the process and not captured by any Try Catch
. To simplify the problem, let's take a look at the case of synchronization.
function external() {
throw new Error(‘Catch me‘);
}
function internal() {
external();
}
internal(); //error will be thrown
Execute the program on the command line, and the script will break on the line that throws the exception. Next, because there is no Try Catch
, the exception will bubble up until the event loop, and Nodejs's default handling of the exception is simple, and the code is processed like this:
function _MyFatalException(err){
if(!process.emit(‘uncaughtException‘,err)){
console.error(err.stack);
process.emit(‘exit‘,1);
}
}
Nodejs default handling for uncaught exceptions is:-Trigger uncaughtException
Event-if uncaughtexception is not listening, then-print exception stack information-triggers the exit event of the process
If you are using NodeJS to develop a server, then you certainly do not want an accidental exception to the entire server hanging out. So uncaughtException
is it possible to stop the server's process from exiting as long as it listens? The answer is yes, but don't do it!. See this example:
var express = require(‘express‘);
function external(cb) {
process.nextTick(function () {
throw new Error();
cb.call(null, ‘sunny‘);
})
}
var app = express();
app.get(‘/weather‘, function (req, res) {
external(function (data) {
res.end(‘Weather of Beijing is ‘ + data);
})
})
app.listen(8018);
function noop(){}
process.on(‘uncaughtException‘, noop)
The above example assumes that when a user visits a site you can see the local weather and we use it apache2-utils
to simulate the request
Ab-n 1000-c Http://localhost:8018/weather
Bad! The request has been waiting for the memory to rise. The reason is that it is res.end
never executed, the existing I/O
waiting state, the resources that have been opened not only will not be released, and the server is also tirelessly accepting new user requests.
Handling exceptions in NodeJS is expensive, and inadvertently causes memory leaks and applications to be in an unstable state. In order to improve robustness, we can use Cluster
patterns, which are recommended by:-Return an error code for an exception request-the worker who made the error no longer accepts a new request-exits the worker process
The writer is ONEAPM engineer Wang Yu, want to read more good technical articles, please visit the ONEAPM Official technology blog.
Nodejs Exception Handling Uncaughtexception article