oak-cli/template/native/promiseTracker/index.ts

46 lines
1.7 KiB
TypeScript

export type PromiseUnCatchHandler = (id: string, error: Error) => void;
const noop: PromiseUnCatchHandler = () => { };
/**
*
* @param {Function} customHandler
* @param {Boolean} allowedInDevMode
* @returns
*/
export const setPromiseUnCatchHandler = (customHandler: PromiseUnCatchHandler = noop, allowedInDevMode = false) => {
if (typeof customHandler !== 'function' || typeof allowedInDevMode !== 'boolean') {
console.log('setPromiseUnCatchHandler is called with wrong argument types.. first argument should be callback function and second argument is optional should be a boolean');
console.log('Not setting the JS handler .. please fix setPromiseUnCatchHandler call');
return;
}
const customRejectionTrackingOptions = {
allRejections: true,
onUnhandled: customHandler,
onHandled: (id: string) => {
const warning =
`Promise Rejection Handled (id: ${id})\n` +
'This means you can ignore any previous messages of the form ' +
`"Possible Unhandled Promise Rejection (id: ${id}):"`;
console.warn(warning);
},
};
// @ts-ignore
const __DEV__ = process.env.NODE_ENV === 'development';
const allowed = allowedInDevMode ? true : !__DEV__;
if (allowed) {
// @ts-ignore
if (global?.HermesInternal?.hasPromise?.()) {
// @ts-ignore
global.HermesInternal?.enablePromiseRejectionTracker?.(
customRejectionTrackingOptions,
);
} else {
require('promise/setimmediate/rejection-tracking').enable(
customRejectionTrackingOptions,
);
}
} else {
console.log('Skipping setPromiseUnCatchHandler: Reason: In DEV mode and allowedInDevMode = false');
}
};