javascript - How to catch exceptions thrown in callbacks passed to jQuery? -
i'd catch exceptions thrown callbacks passed jquery (either event handlers click, or jqxhr methods such then or always).
i've identified 2 options:
window.onerrorhandler - partial solution because isn't supported on android 1 of target platforms- handling exceptions within each individual callback - not dry @ all!
the other thing can think of overriding jquery methods can result in problems time upgrade jquery. ajax handlers, possibly use $.ajaxsetup (per answer exceptions thrown in jquery ajax callbacks swallowed?) i'm not sure allow me catch everything.
are there other options?
you can wrap each callback this:
function cbwrapper(fn) { return function() { try { return(fn.apply(this, arguments)); } catch(e) { // handle exceptions here } }; } so, when go pass callback ajax call, instead of passing actual callback, pass cbwrapper(callback).
$.get(url, cbwrapper(myrealcallback)); or inline anonymous version this:
$.get(url, cbwrapper(function() { // actual callback code here })); a more advanced way of doing override $.get() own implementation wraps callback automatically, gets tricky because jquery flexible arguments passed. because of , because have override 1 specific argument make work, have duplicate of argument detection code figures out arguments present , correspond actual function parameters. code bit messy. it's doable , won't break because if jquery broke it, existing jquery code break, isn't clean.
if it's own code, make own version of $.get() isn't flexible argument positions , switch of code use instead of actual $.get():
jquery.fn.myget = function(url, fn) { return(jquery.get(url, cbwrapper(fn))); }
Comments
Post a Comment