Any problems with handling a JavaScript exception by throwing in a setTimeout()?
javascript
Solution
If you want to just report an error in the console without interrupting the execution, use
console.error(e);
instead. It may cause some issues in IE, since `console` is not defined while development tools not opened. So you can either do
console = window.console || {error: function(){}};
somewhere at the beginning of your code, or if it is a single place you want to report an error
console && console.error(e);
EDIT:
If you want to throw error anyway, it is not necessary to wait for a long time - you can do
setTimeout(function() {
throw new Error('Some meaningful error message. Caused by: ' + e.toString());
}, 0);
that will be executed once UI thread is in the idle mode. I also recomend to rethrow exception with meaningful description since you aready know where (and probably why) it is happened.
Problem
I have a function that may throw an exception. I would like to expose that exception as if it were thrown (essentially the same UI experience, so that it shows as an exception in the browser window and console, any debug tools). But I don't want the exception to halt execution of the original function. One solution to this problem is catching and re-throwing the exception but inside a setTimeout(). That way it will be invoked later but without interrupting the function where it originally occurred. Example: ``` var f = function() { try { // exception could throw in here somewhere } catch (e) { setTimeout( function() { throw e; }, 100 ); } } ``` My question is, are there any pitfalls to this approach? (Besides the obvious, that it may delay reporting slightly?) Or is this a relatively safe and well-accepted idiom in the JavaScript community? Are there any minor improvements to be made? Clarification: I'd like to avoid console.log and console.error because they are non-standard, and console.log does not have the same user experience as `throw e`.