Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent console closing on exception

I'm trying out Visual Studio Code (on Windows) and liking it so far.

Is there a way to prevent the console/terminal from closing automatically on an unhandled exception when debugging a node app?

I know that node exiting is the correct behavior, I just like a chance to read the output before closing the console window.

like image 819
Simon Avatar asked Apr 30 '15 13:04

Simon


2 Answers

If you attach an event handler to the process object watching for uncaughtException, that code will be called immediately in the case of an unhandled exception:

process.on('uncaughtException', UncaughtExceptionHandler);

function UncaughtExceptionHandler(err)
{
    console.log("Uncaught Exception Encountered!!");
    console.log("err: ", err);
    console.log("Stack trace: ", err.stack);
    setInterval(function(){}, 1000);
}

This will output the error, the stack trace, and then wait forever for you to kill program manually that you are debugging. This will be helpful for debug, but obviously not something you'd want in a final product.

When I add the code "console.log(undefined.undefined);" after the process.on statement above, I get the resulting output:

Uncaught Exception Encountered!
err:  [TypeError: Cannot read property 'undefined' of undefined]
Stack trace:  TypeError: Cannot read property 'undefined' of undefined
    at Object.<anonymous> (/home/username/Desktop/test.js:3:22)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

It then "pauses" forever until I kill the program.

like image 92
Brian Avatar answered Nov 12 '22 01:11

Brian


enter image description here

One good and neat solution for windows is to make a run-server.bat Open the file with code editor and write the following codes. What this does, run the server and if server exits, just pause the console.

node server.js
PAUSE
like image 44
Caezar Vibal De Castro II Avatar answered Nov 12 '22 00:11

Caezar Vibal De Castro II