Skip to main content

imp.onunhandledexception(errorHandler)

Registers a global error handler

Availability

Device + Agent

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 exception 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, when the following code is executed:

try {
    wakeup();
} catch(exception) {
    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 exception handler if one has been registered:

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

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 exception 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 exceptions thrown at runtime.

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

If the error handling function itself throws 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.