diff --git a/src/utils/ensure.ts b/src/utils/ensure.ts new file mode 100644 index 0000000..e2b9459 --- /dev/null +++ b/src/utils/ensure.ts @@ -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(fn: () => Promise): Promise { + try { + return await fn(); + } catch (err) { + throw ensureError(err); + } +} + +export default { + error: ensureError, + rejection: ensureRejection +};