Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active October 7, 2019 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinobney/5aa041178c31f676031d9f8e2b86a08d to your computer and use it in GitHub Desktop.
Save justinobney/5aa041178c31f676031d9f8e2b86a08d to your computer and use it in GitHub Desktop.
type GuardedResult<ReturnType, DefaultValueType = ReturnType> = ReturnType | DefaultValueType;
type GuardedFn<ReturnType, DefaultValueType = ReturnType> = (
...args
) => GuardedResult<ReturnType, DefaultValueType>;
function guard<ReturnType, DefaultValueType = ReturnType>(
fn: GuardedFn<ReturnType, DefaultValueType>,
defaultValue: GuardedResult<ReturnType, DefaultValueType>
) {
const guarded: GuardedFn<ReturnType, DefaultValueType> = (...args) => {
try {
return fn(...args);
} catch (error) {
return handleError(error, defaultValue);
}
};
return guarded;
}
function guardAsync<ReturnType, DefaultValueType = ReturnType>(
fn: GuardedFn<Promise<ReturnType | DefaultValueType>>,
defaultValue: GuardedResult<Promise<ReturnType | DefaultValueType>>
) {
return guard<Promise<ReturnType | DefaultValueType>>(
(...args) =>
fn(...args).then(x => x, error => handleError(error, defaultValue)),
defaultValue
);
}
function handleError<T>(error: Error, defaultValue: T): T {
if (isProductionBuild) {
Sentry.captureException(error);
} else {
handleDevelopmentError(error);
}
return defaultValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment