Is there a way to add try-catch to every function in Javascript?
This isn't simple since there is no way to find all JavaScript function defined everywhere. For example, any such approach would probably miss callback functions which are defined at runtime.
You also probably don't want to wrap all functions because that would include browser functions and functions from JavaScript libraries that you certainly don't want to wrap.
A much better approach is probably to define a function which wraps another function:
var tcWrapper = function(f) {
return function() {
try {
f.apply(this, arguments);
} catch(e) {
customErrorHandler(e)
}
}
}
Now you can use this function to decorate anything that you want. Wrapping will become more simple if you use name spaces:
var NS = { f: function() { } }
Just put all functions to wrap in a special namespace and then iterate over the namespace:
$.each( NS, function(i,n) {
var p = NS[i];
if( typeof p === 'function' ) {
NS[i] = tcWrapper(p);
}
} );
I don't have enough reputation to comment on the accepted answer.
I added a return
before the f.apply
to pass up the return value as well.
var tcWrapper = function(f) {
return function() {
try {
return f.apply(this, arguments);
} catch(e) {
customErrorHandler(e)
}
}
}
The given answers already work well, just wanted to share a new one using closures.
Define wrapper
const tryCatchWrapper = (executable) => async (...args) => {
try {
const result = await executable(...args);
return result;
} catch (error) {
// use any custom handler here
error.message = `[${executable.name}] - ${error.message}`;
error.data = {...error.data, input_args: args}
throw error;
}
}
Your function without a try-catch wrapper
const myFunction = async (x, y) => {
const sum = x + y;
if (sum > 10) throw new Error(`sum > 10 custom error`)
return sum;
}
How to use it
try {
const wrapperFunction = trycatchWrapper3(myFunction2);
const output = await wrapperFunction(2, 93)
console.log(output)
} catch (error) {
console.error(error)
}