Skip to main content

imp.onunhandledexception(errorHandler)

Registers a global error handler

Availability

Device (from impOS™ 38)

Parameters

Name Type Description
errorHandler Function The function called when an untrapped error occurs

Returns

Nothing

Description

This method registers a global error handling function that is able to trap any Squirrel error which takes place outside of Squirrel’s own try… catch structure. It is typically used to catch errors which arise within closures: clones of functions that are stationed to run asynchronously in response to a timer being fired or some other event taking place.

For example, in the following code:

try {
    wakeup();
} catch(exc) {
    server.error("Locally caught error: " + exception);
}

the index 'wakeup' does not exist error is caught by the try… catch statement and reported, but execution continues. However, the following variation of the code:

try {
    imp.wakeup(0, function() {
        wakeup();
    });
} catch(exception) {
    server.error("Locally caught error: " + exception);
}

does not trap the error — instead the imp restarts. This is because the function executed by the imp.wakeup() timer is a closure and thus out of the scope of the try… catch statement. However, the error will be caught by a global error handler if one has been registered:

imp.onunhandledexception(function(err) {
    server.error("Globally caught error: " + err);
});

try {
    imp.wakeup(0, function() {
        wakeup();
    });
} catch(exception) {
    server.error("Locally caught error: " + exception);
}

ie. we will see [Error] Globally caught error: the index 'wakeup' does not exist: in unknown device_code:24 displayed in the log.

You should note that, unlike catch, the global error handler function can’t prevent the error from causing the Squirrel VM to restart, which will happen when the function returns. As such, the method is intended to aid application debugging, not as a means to mitigate runtime errors.

The function passed as an argument into the errorHandler parameter has one parameter of its own: error, into which an error message string is passed when the function is called. The message indicates the nature of the error and, in most cases, the function and/or line number at which the error occurred.

If the error handling function itself raises an exception, or attempts to suspend the host imp (for example, by calling server.log() when the device is disconnected), then the following additional error will be logged:

error or suspend in exception handler

It is recommended that the handler is kept simple to avoid secondary errors, for which a backtrace is currently unavailable.