Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active June 27, 2019 16:16
Show Gist options
  • Save justinobney/96cfceda9dc7aeb109aebe7fd2d93a7a to your computer and use it in GitHub Desktop.
Save justinobney/96cfceda9dc7aeb109aebe7fd2d93a7a to your computer and use it in GitHub Desktop.
const parse = guard(input => JSON.parse(input), {});
/**
* - Will always be an object
* - Don't have to clutter with try/catch
* - Can test if the returned value is default value to know success
* - In development errors are logged to console and browser notifications sent
* - In development notifications mesages are cached to not spam developer
* - In production, errors are sent to error logging service
*/
const data = parse(event.data);
import * as Sentry from '@sentry/browser';
import {last} from 'lodash';
import {StackFrame} from 'stacktrace-js';
function guard(fn, defaultValue) {
return (...args) => {
try {
return fn(...args);
} catch (error) {
if (process.env.NODE_ENV === 'production') {
Sentry.captureException(error);
} else {
handleDevelopmentError(error);
}
return defaultValue;
}
};
}
function parseErrorInfo(error: Error) {
const errorStackParser = require('error-stack-parser');
const stackInfo = last<StackFrame>(errorStackParser.parse(error));
if (!stackInfo) {
return {
title: error.message,
cacheKey: error.message || 'Unknown function name',
};
}
return {
title:
stackInfo.functionName ||
stackInfo.fileName ||
stackInfo.source ||
'Unknown function name',
cacheKey: stackInfo.source || error.message || 'Unknown source',
};
}
const developmentErrorNotificationCache = {};
function handleDevelopmentError(error: Error) {
const notifications = require('simple-web-notification');
const errorInfo = parseErrorInfo(error);
if (!developmentErrorNotificationCache[errorInfo.cacheKey]) {
developmentErrorNotificationCache[errorInfo.cacheKey] = true;
if (console.groupCollapsed) {
console.groupCollapsed(`caught guarded error (${errorInfo.title})`);
}
console.error(error);
if (console.groupEnd) {
console.groupEnd();
}
notifications.showNotification('Console Error', {
body: errorInfo.title,
icon: 'my-icon.ico',
});
}
}
export {guard};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment