All files / src/hof guarded.js

9.09% Statements 1/11
0% Branches 0/6
0% Functions 0/3
9.09% Lines 1/11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 331x                                                                
const DEFAULT_CONFIG = {
	context: null
};
 
function logError(err) {
	console.error(err.stack || err);
	for (let key in err) {
		if (key !== 'stack') {
			console.error(`${key} = ${err[key]}`);
		}
	}
}
 
// [HOF]
//
// returns a guarded version of a given async function.
// Errors are logged during synchronous or asynchronous execution
export default function guarded(asyncFn, config) {
	config = {
		...DEFAULT_CONFIG,
		...(config || {})
	};
 
	return async function guardedFn(...args) {
		try {
			return await asyncFn.apply(config.context, args);
		} catch (err) {
			logError(err);
			throw err;
		}
	};
}