@replygirl/tc

destructurable, async-friendly `try...catch` wrapper function with support for error side effects and fallback values

Usage no npm install needed!

<script type="module">
  import replygirlTc from 'https://cdn.skypack.dev/@replygirl/tc';
</script>

README

tc

node-current (scoped) GitHub top language Libraries.io dependency status for latest release, scoped npm package Maintainability Test Coverage GitHub issues GitHub pull requests

destructurable, async-friendly try...catch wrapper function with support for error side effects and fallback values

Installation

yarn add @replygirl/tc

Usage

Basic

import tc from '@replygirl/tc'

const [x] = await tc(async () => true)
console.info(x) // true

const [y, e] = await tc(async () => { throw new Error() })
console.info(y ?? e) // Error

Sync variant: tcs (no Promises or async/await)

import { tc } from '@replygirl/tc'

const [x] = tc(() => true)
console.info(x) // true

const [y, e] = tc(() => { throw new Error() })
console.info(y ?? e) // Error

Custom error handling

await tc(
  async() => { throw new Error() },
  async e => console.error(e)
) // Error

Returning fallback values in error handlers

const [y] = await tc(
  async () => { throw new Error() },
  async e => false
)
console.info(y) // false

TypeScript

If you need to override the inferred return type of your callback or error handler (let's say your error handler returns void instead of matching your callback), tc and tcs both accept T and U parameters that represent the unwrapped values of each:

declare function tc <T = unknown, U = T>(
  cb: () => Promise<T>,
  fb?: (e?: unknown) => Promise<U>
): Promise<[(T | U)?, unknown?]>

declare function tcs <T = unknown, U = T>(
  cb: () => T,
  fb?: (e?: unknown) => U
): [(T | U)?, unknown?]

License

ISC (c) 2020 replygirl