UNPKG

berrserk

Version:

Lightweight TypeScript library for type-safe errors-as-values

18 lines (17 loc) 487 B
function withError(callback) { try { const result = callback(); const isPromise = result instanceof Promise; if (!isPromise) return getSuccess(result); return result.then(getSuccess).catch(getFailure); } catch (error) { return getFailure(error); } } const getFailure = (error)=>({ error: error instanceof Error ? error : new Error(String(error)) }); const getSuccess = (data)=>({ data }); export { withError };