I use amazing J2V8 java library which allows execute any Javascript code in your Java application furthermore it can integrates a nodeJS engine.
But i have encountered with a next issue. This code interrupts a Java application immediately after nodejs invokes a callback function of setTimeout which throw an exception although there is a try..carch block. The exception doesn't even enter into the try..catch block.
// It is an example, in real case it can be a some erorr in a code.
nodeJS = NodeJS.createNodeJS();
try {
nodeJS.getRuntime().executeVoidScript("setTimeout(function(){throw 'Error'}, 1000);");
} catch (Exception e) {
e.printStackTrace();
}
The application is interrupted with message:
undefined:1
setTimeout(function(){throw 'Error'}, 10000);
^
Error
Process finished with exit code 1
Another example shows that exceptions are not a cause of interruption of an application always and it is a 'normal' case.
nodeJS = NodeJS.createNodeJS();
try {
nodeJS.getRuntime().executeVoidScript("throw 'Error'");
} catch (Exception e) {
e.printStackTrace();
}
In this case we see the only a error message in console but the application still works.
Exception in thread "Thread-2" undefined:1: Error
throw 'Error'
^
com.eclipsesource.v8.V8ScriptExecutionException
at com.eclipsesource.v8.V8._executeScript(Native Method)
at com.eclipsesource.v8.V8.executeScript(V8.java:940)
at com.eclipsesource.v8.V8.executeScript(V8.java:595)
at com.eclipsesource.v8.V8.executeObjectScript(V8.java:625)
at com.eclipsesource.v8.V8.executeObjectScript(V8.java:608)
at org.efc.origamiapp.v8.V8Environment.run(V8Environment.java:383)
The examples above are in the try..catch blocks, and you can see trace stack below it. So the interruption is fired in Native Method (the secod example), but in the first case the JS exception just kills the Java application without any explanations in a console or in a trace log.
This is the best and correct solution.
process.on('unhandledRejection', (err) => {
console.error('Unhandled promise rejection',err);
});
process.on('uncaughtException', (err) => {
console.error('Uncaught exception',err);
});
For more information see the nodeJS documentation: Event: 'uncaughtException'