Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  94] [ 7]  / answers: 1 / hits: 15659  / 14 Years ago, mon, june 21, 2010, 12:00:00

Is there any way I could catch any uncaught exception in javascript? I mean, all my dangerous code are in try-catch blocks. But what about exceptions that I don't handle explicitly? I'm using jQuery, my main javascript file starts with :



$(document).ready(function(){})



here I bind some events to some DOM elements. I can use try-catch blocks here, but they will catch exceptions that occur during the event binding procedure, not during the event handling. But if I used try-catch blocks in every event handling functions it would be ugly.



How should I catch exceptions that don't occur in my explicit try-catch blocks? (I don't want to write a general handler function, I just want to send the problem to my server)


More From » jquery

 Answers
2

You could write a function that would wrap your real handlers in a try/catch



function tc(func, msg) {
msg = msg || Handler exception;
return function(e) {
try {
return func(e);
}
catch (exc) {
$.post( /* send exception to server? */ );
throw exc; // let nature take its course
}
};
}


(Might want to get fancier with argument handling etc.) Then when you bind handlers you'd do:



$('#whatever').click(tc(function(e) {
// your handler function
}, This is the message sent to the server when this handler fails));


Also, if you want to make sure this in the handler behaves as before, you can do func.apply($(this), e) instead of just func(e).


[#96438] Thursday, June 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;