Skip to content

Commit

Permalink
feat(utils): adds ensure
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed Apr 11, 2019
1 parent f5b179b commit 91d12ab
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/utils/ensure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export const DEFAULT_MESSAGE = 'An error occurred';

function ensureError(err?: any): Error {
if (err instanceof Error) return err;
return err && typeof err === 'object' && err.hasOwnProperty('message')
? Error(err.message)
: Error(typeof err === 'string' ? err : DEFAULT_MESSAGE);
}

async function ensureRejection<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn();
} catch (err) {
throw ensureError(err);
}
}

export default {
error: ensureError,
rejection: ensureRejection
};

0 comments on commit 91d12ab

Please sign in to comment.