Electron Crashing On Exception, Even With uncaughtException Handled - node.js

Im trying to prevent my application crashing when and unhandled exception occurs.
I've added a
process.on("uncaughtException", err => {
dialog.showErrorBox("Uh oh...", `${err}`);
});
and im just triggering a false exception by calling a function that doesn't exist inside of a main process method, triggered by a button click and an IPC call from the rendered UI.
start() {
this.blah(); // ReferenceError blah is not defined
}
to my main process file, although now I just get two dialogs, the first default electron one, showing the stack track and error, then the one prompted by me, followed by the application crashing.
So it appears it's hitting the uncaught exception handler, although it just pops up the dialog and continues.
How can I prevent the app from crashing, and only display the one dialog box from my handler?

Related

Run a function when a ClientEmitter has an error

I'm using an event handler, where each event code is in it's own files. I'm attaching the events to the client, so when that file has the event emitted, it will run that code:
// looping through all event files
client.on(file.split('.')[0], require(`events/${file}`).bind(null, client, Util);
If the event file was message.js, it would be similar to:
client.on('message', require('events/message.js').bind(null, client, Util);
So when the message event is emitted, it runs the message.js file, passing along the client and Util classes.
I also have a function that is attached to the client called report. It basically reports when there is an error. I would like it so whenever any event from the client has an error, it will run that function.
I've done this slightly with the commands: command.run(...).catch(error => client.report(error)).
Is there a similar way to do this, instead of having to put a try-catch around all code in all the event files?
Try this way
client.on('error', require('events/report.js').bind(null, client, Util);
Error handling should be context driven. This means your bot's response to the error should be dependent on what it was doing, in what channel, etc - both for debugging and for the end user's information on what happened. You'll miss out on all of the context by letting errors just travel all the way up into an uncaught exception, and without the ability to create an error message, the user will just see the bot not respond and think it's down or the command is broken.
My suggestion: Create helper methods for your most common error producing functions that wrap them with error handling. I did this mostly for sending messages, as there's a myriad of things that could cause a message send to fail out of your control and the handling consists of generating an error message and attempting to send it in the channel or DM it to the user if that fails.

Error: Cannot access a disposed object Xamarin.Forms

How can I catch which object is disposed from Xamarin.Forms app. The problem occurs when I am navigating between pages more specific on PopAsync(), But my question is in general how to catch which one is the disposed object. Thanks.
The name of the disposed object should be part of the Exception's stack trace. Try to dive into the exception message or inner exception to see if it is there.
In addition you could go to Debug -> Windows -> Exception Settings, search for System.ObjectDisposedException and check the checkbox next to it to make debugger stop when it encounters this exception.

How to define a request timeout on asp.net core MVC on linux

Given:
ASP.Net Core MVC application, deployed in docker containers on linux.
Nginx reverse proxy + load balancer
When the ASP.Net core container gets stuck (after a timeout on nginx), it calls a different instance of the application. At that point, the application should cancel the processing in order to not perform data manipulation operations twice. This works great with a global:
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
using (context.HttpContext.RequestAborted.Register(() => context.HttpContext.RequestAborted.ThrowIfCancellationRequested()))
{
await base.OnActionExecutionAsync(context, next);
}
}
The problem here is, that nginx might cancel the request, right after the transaction in the controller and underlying services completed. Which means, the request was successful, but just slightly too long, and nginx will try a second time anyway. In order to solve this, we wanted to set a second timeout which would be few seconds shorter than nginx timeout. The only solution I've found is this:
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var timeout = new CancellationTokenSource();
timeout.CancelAfter(ActionTimeout);
using (timeout.Token.Register(() => timeout.Token.ThrowIfCancellationRequested()))
using (context.HttpContext.RequestAborted.Register(() => context.HttpContext.RequestAborted.ThrowIfCancellationRequested()))
{
await base.OnActionExecutionAsync(context, next);
}
}
But this is throwing the following exception:
System.AggregateException was unhandled
Message: An unhandled exception of type 'System.AggregateException' occurred in System.Private.CoreLib.ni.dll
Additional information: One or more errors occurred.
And afterwards the application is crashing. Putting try/catch anywhere around of course also doesn't help and adding a global exception filter to the middleware doesn't help either.
What is the best way to cancel Requests on linux after a custom timout, without depending on a reverse proxy to do it?
Update - details on exceptions:
At first I see the following exception:
System.OperationCanceledException was unhandled by user code
HResult=-2146233029
Message=The operation was canceled.
Source=System.Private.CoreLib
StackTrace:
at System.Threading.CancellationToken.ThrowOperationCanceledException()
at ...BaseController.<>c__DisplayClass4_0.<OnActionExecutionAsync>b__0() in ...\Controllers\BaseController.cs:line 28
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
InnerException:
Which is fine, that's the cancellation token throwing the exception. But the second one, the one which I can't catch, not sure how I could see the details there, I just see the following screen:
And regardless of what I tried, the process always stopped afterwards (even if I press continue execution)

error when calling agent from xpage button

I am receiving an error when trying to call an agent from an xpages button click: Error below
Error while executing JavaScript action expression
Script interpreter error, line=2, col=7: [TypeError] Exception occurred calling method NotesAgent.runWithDocumentContext(lotus.domino.local.Document) null
JavaScript code
var agent=database.getAgent("xpCreateNewCopy");
agent.runWithDocumentContext(currentDocument.getDocument());
I had missed an important setting, run as web user. Problem solved.

Node Exception Handling

What is the best way in node to handle unhandled expections that are coming out of core node code? I have a background process that runs and crawls web content and will run for long periods of time without issue, but every so often an unexpected exception occurs and I can't seem to gracefully handle it. The usual culprit appears to be some networking issue (lost connectivity) where the http calls I'm making fail. All of the functions that I have created follow the pattern of FUNCTION_NAME(error, returned_data), but in the situations where the error occurs I'm not seeing any of the functions I created in the call stack that is printed out, instead its showing some of the core node modules. I'm not really worried about these infrequent errors and their root cause, the purpose of this posting is just trying to find a graceful way of handling these exceptions.
I've tried putting a try/catch at the top level of my code where everything runs under but it doesn't seem to capture these exceptions. Is it good practice in node to use try/catch within all the lower level functions that use any core code? Or is there some way to globally capture all unhandled exceptions?
Thanks
Chris
UPDATED TO ADD STACK
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect Unknown system errno 10060
at errnoException (net.js:642:11)
at Object.afterConnect [as oncomplete] (net.js:633:18)
is there some way to globally capture all unhandled exceptions?
You can catch all exceptions using process.on('uncaughtException'). Listening to this event will avoid the default action of printing the stack and exiting. However be conscious that ignoring exceptions may lead to problems in your app execution.
Link: http://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception
Pay attention to the documentation advice:
Note that uncaughtException is a very crude mechanism for exception handling. Using try / catch in your program will give you more control over your program's flow. Especially for server programs that are designed to stay running forever, uncaughtException can be a useful safety mechanism.
To catch network errors and avoid the default behavior (printing stack and exit) you have to listen to "error" events.
For example
var net = require('net');
var client = net.connect(80, 'invalid.host', function () {
console.log("Worked");
})
client.on('error', console.log);
I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post and in the docs.
You can use domains to handle callback error arguments, error event emitters and exceptions all in one place. The problem in this specific case is that when you dont handle an error event emitter, node by default will print the stack trace and exit the app.
I've put together a quick error handling file which logs and emails me whenever an unhandled exception is thrown. it then (optionally) tries to restart the server.
Check it out!

Resources