Skip to content

Instantly share code, notes, and snippets.

@honewatson
Created October 4, 2018 23:32
Show Gist options
  • Save honewatson/fcaf3bbceffc5eec1254f0453839d234 to your computer and use it in GitHub Desktop.
Save honewatson/fcaf3bbceffc5eec1254f0453839d234 to your computer and use it in GitHub Desktop.
Betters Stack Traces For Javascript FP
const warningMessage = (fn) =>
`Error running function '${fn.name}' with args:`
const composeReducer = (f, g) => (...args) => {
var fResult, gResult;
try {
gResult = g(...args);
} catch (e) {
console.warn(warningMessage(g), args);
throw e;
}
try {
fResult = f(gResult);
} catch (e) {
console.warn(warningMessage(f), gResult);
throw e;
}
return fResult;
};
const compose = (...fns) => fns.reduce(composeReducer);
// USAGE
// compose function
const __copy = compose(JSON.parse, JSON.stringify);
// define api
const copy = (data) => __copy(data);
const title = (str) => `<h1>${str}</h1>`;
// compose function
const __safeTitle = compose(title, copy);
// define api
const safeTitle = (str) => __safeTitle(str);
safeTitle();
// Error running function 'parse' with args: undefined
// Error running function 'copy' with args: [undefined]
// Uncaught SyntaxError: Unexpected token u in JSON at position 0
// at parse (<anonymous>)
// at args (<anonymous>:13:19)
// at copy (<anonymous>:29:24)
// at args (<anonymous>:7:19)
// at safeTitle (<anonymous>:37:28)
// at <anonymous>:1:1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment