process.on('uncaughtException') doesn't work everytime?

73 views
Skip to first unread message

William Lin

unread,
Mar 17, 2016, 12:16:52 PM3/17/16
to nodejs
Hello,
I put this in my code:
process.on('uncaughtException', function(err){
  console.error(err.stack);
  console.log("Node NOT Exiting...");
});
If I do something like 
nonExistingFunction();
,then it will catch the error, but my script always stops with the error
events.js:141
  throw err;
something like that.

Can anyone help me?
Thank you.

P.S. I'm using socket.io and express.



Atnakus Arzah

unread,
Mar 23, 2016, 12:12:24 AM3/23/16
to nodejs
On Wed, Mar 16, 2016 at 04:40:57PM -0700, William Lin wrote:
>Hello,
>I put this in my code:
>process.on('uncaughtException', function(err){
> console.error(err.stack);
> console.log("Node NOT Exiting...");
>});
>If I do something like
>nonExistingFunction();
>,then it will catch the error, but my script always stops with the error
>events.js:141
> throw err;
>something like that.
>
>Can anyone help me?
>Thank you.
>

I tried with the below code. When I press CTRL-C, the SIGINT is trapped and it
calls an undefined function, which then results in the uncaughtException part
of the code to execute. Note that if you have nonExistingFunction() at the top
level then the node compiler will detect it before it has a chance to execute.


setInterval(function () { console.log("hello I am alive");}, 1000);

process.on('SIGINT', function() {
console.log('Got SIGINT. Calling a nonExistingFunction');
nonExistingFunction();
});


process.on('uncaughtException', function(err){
console.log("Okay caught an unhandled exception");
// console.error(err.stack);
process.exit(-1);
});

Below are the results of the run:

hello I am alive
hello I am alive
hello I am alive
hello I am alive
^CGot SIGINT. Calling a nonExistingFunction
Okay caught an unhandled exception




--
Atnakus Arzah <atnaku...@gmail.com>

When in doubt, have a cookie!

signature.asc

Will Hoover

unread,
Mar 23, 2016, 10:51:01 AM3/23/16
to nodejs
Have you tried listening for "exit" in addition to "SIGINT" and "uncaughtException"?

process.on('exit', (code) => {
// do something
});
--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/20160323023010.GA5069%40Sukantas-MacBook-Pro.local.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages