How to catch random exceptions


#1

I’m handling every exception I can, but sometimes modules throw exceptions I have no way to catch (AFAIK). For example, this code to read compressed data streams:

    var request = https.get(url, function(response) {
        switch (response.headers['content-encoding']) {
        case 'gzip':
            response.pipe(zlib.createGunzip()).pipe(file);
            break;

(etc) will sometimes put up a dialog like this:

A Javascript error occurred in the main process
Uncaught Exception:
Error: unexpected end of file
at Zlib._handle.onerror (zlib.js:363:17)

If the web server doesn’t serve the file completely or something. I handle the error anyway, so I’m wondering if there is a way to change the way uncaught exceptions are handled. I don’t want my users seeing random messages like that. I would rather just suppress them in production code, or put in my own handler so I can write them quietly someplace.

I can’t find an API for that.

(And I’m guessing there might be a way to register for that error with zlib, but I’ve seen myriad random exceptions thrown by various modules, so I’m looking for more of a last-resort error handling scheme for stuff I cannot catch.)


#2

It looks like Atom overrides window.onerror:


#3

I’m afraid I’m too new here to understand what that implies. Is there a way I can intercept those calls in my main.js? I’m using the pre-built, so changing the source is not a great option for me.


#4

No answer? I looked at that code, and I think I need to do something like:

{what goes here?}.on('will-throw-error', function(event) {
    event.preventDefault();
    console.log(event.url+":"+event.line);
    console.log(event.message);
    console.log(event.originalError);
})

But I can’t figure out what goes there. “Atom Environment” doesn’t seem to be exposed in the “electron” object.


#5

What you’re looking for is what is called an “uncaught exception handler”. You should be able to find out how to handle this in the Chrome documentation or on StackOverflow. Though the code I included above is a good example … the key is onerror (sounds like “on error”).


#6

The exception is happening in the main.js of my Electron application, not in the content running in Chrome, per se. To what object in electron am I assigning an “onerror” handler?

For example, if I were going to handle uncaught exceptions in the quick start app from the docs, how would I do that?


#7

For that, you’ll probably want to look at the Node documentation to see if there is any way they provide to handle uncaught exceptions.


#8

Use process.on('uncaughtException', function () { ... }) as documented.


#9

Thank you! That totally worked!