I have a function like so:
const x = y(callback);
x();
It may be called with a synchronous or asynchronous callback:
const a = y(() => 42);
const b = y(async () => Promise.resolve(42));
The function y
should take a callback, that can be synchronous or asynchronous. Is it possible to catch a thrown error from either a synchronous or asynchronous callback?
I can't simply wrap the callback in a try/catch
:
const y = (callback) => function () {
try {
return callback(...arguments);
}
catch (callbackError) {
throw callbackError;
}
};
because that doesn't catch the errors thrown from promises. I can't just chain a .catch
onto the callback as it might not be a promise.
I've read that checking if a function is a promise before calling it may not trivial/may not be possible.
I can't call it to check if it returns a promise before chaining the catch
onto it because if it throws, the catch
would not have yet been chained onto the call
Is there a way to catch an error from a callback that may or may not be a promise?
Per the comments, I should have specified I don't want the function to return a promise. That is:
const a = y(() => { throw new Error(); })();
console.log(a instanceof Error);
const b = y(async () => { throw new Error(); })();
console.log(b instanceof Error);
const c = y(() => 42)();
console.log(c === 42);
const d = y(async () => Promise.resolve(42))();
console.log(d instanceof Promise);
should all be true. Simply put, I want to return an error or the result