idea: try/catch and "rethrow"...?

Kyle Simpson getify at
Tue Feb 1 10:53:56 PST 2011

?I have something that annoys me about how JavaScript try/catch error 
handling currently works. Don't get me wrong, I totally understand why it 
works that way, and it makes sense. But having the option to get around that 
behavior would be really nice.

My idea/proposal is illustrated with this gist:

Essentially, what I'm running into is several different use-cases for the 
need to wrap a try/catch around some call, and "observe" if it error'ed or 
not. Notice in the code snippet that I'm "modifying" the error's message 
string before re-throwing it. However, that's only one use-case. I might 
very well not need to modify the error, but simply passively "observe" (ie, 
not interfere with the bubbling up of that error) and for instance do some 
sort of cleanup or other graceful handling, and then pass the error along to 
continue its bubbling.

The reason for not wanting to interfere is in the sense of wanting the 
original error to maintain its original execution context (almost like an 
error propagation "stack" if you will), so that when the browser/engine 
reports the uncaught error, it reports it from the correct origination point 
(source file, line-number, etc).

If you try/catch such an error, and then "re-throw" it, that context is 
lost. I'm not positive, but I'm guessing that perhaps this is intentional 
by-design, and not just a particular implementation detail. If it *is* 
standardized, I'm proposing an alternative/addition. If not, I'm proposing 
we standardize a way to both preserve and explicitly not-preserve (aka, 
override) the original context. For compat reasons, the default would 
certainly stay as it currently is, with my idea being opt-in if the author 
needs it.

Of course, JavaScript doesn't expose the internals like the original context 
source file/line-number/etc (although I kinda wish it would), so for purely 
JavaScript sake it really doesn't matter. But I'm running into this in the 
server-side JavaScript world numerous times, and wishing the engine could 
keep that context. It's also useful for debugging purposes when looking at 
JavaScript errors reported in the browser's error console, for instance.

I'm interested in thoughts on either snippet's approach and the feasibility 
of something like this?

--Kyle Simpson


More information about the es-discuss mailing list