jQuery.Deferred.getErrorHook()


jQuery.Deferred.getErrorHook()Returns: Error

Description: Return an Error instance with a defined stack.

Note: This API is not defined by default, but jQuery will make use of it when defined.

When jQuery.Deferred.getErrorHook is defined, it extends the jQuery.Deferred features added in jQuery 3.0 to include an error captured before the async barrier whenever a Deferred throws an exception. This makes it easier to find programming errors that occur inside Deferreds. You can find an example implementation you can copy-paste below, or you can use jquery-deferred-reporter plugin.

1
2
3
4
5
6
7
jQuery.Deferred.getErrorHook = function() {
try {
throw new Error( "Exception in jQuery.Deferred" );
} catch ( err ) {
return err;
}
};

When defined, an error returned by this API is passed to jQuery.Deferred.exceptionHook as the second parameter.

Why does this API exist?

Prior to jQuery 3.0, Deferreds would simply terminate and the browser would generate a message on the console if an exception occurred such as attempting to call an undefined method as a function (e.g., myobject.missingFunction()). As of version 3.0, jQuery.Deferred follows the Promise/A+ specification when you use the .then method. The spec requires all errors to be trapped by the Promise, which prevents console errors from being logged. If the user has forgotten to add a handler for rejected promises, this can result in the error being silently swallowed with no notification at all!

The native Promise object as implemented in the browser tracks Promise rejections and reports problems on the console. However, doing the same type of reporting in the JavaScript world is much more difficult. jQuery itself is unable to use the native Promise because jQuery.Deferred implements a superset of Promise that requires additional features for methods like .done or .fail, and because Promise is not implemented on all the platforms that jQuery supports.