@sharyn/util.trycatch

tryCatch: An inline try / catch / finally function, which returns the result of the try or catch case.

Usage no npm install needed!

<script type="module">
  import sharynUtilTrycatch from 'https://cdn.skypack.dev/@sharyn/util.trycatch';
</script>

README

🌹 tryCatch

tryCatch: An inline try / catch / finally function, which returns the result of the try or catch case.

Installation

npm i @sharyn/util.trycatch
# or
yarn add @sharyn/util.trycatch

You can alternatively install the @sharyn/util package, or the entire sharyn library.

Arguments

tryFn (function): The try instructions in a function.

[catchFn] (function): The catch instructions in a function. Called with the error.

[finallyFn] (function): The finally instructions in a function.

Returns

any: What your tryFn or catchFn functions return.

Example

tryCatch(() => success()) // some result
tryCatch(() => failure()) // undefined
tryCatch(() => failure(), err => err) // the error
tryCatch(() => failure(), () => {}) // undefined
tryCatch(() => whatever(), () => {}, () => cleanup())

Is is particularly useful to avoid this pattern of assigning a variable inside the try block:

let result
try {
  result = somethingRisky()
} catch (e) {
  handleError(e)
}

Which can be replaced by one line:

const result = tryCatch(() => somethingRisky(), e => handleError(e))

Please note that tryCatch may affect the linting or type-checking of that code compared to using a real try / catch block.

Imports

Depending on the package you are using, you can import or require tryCatch in the following ways:

// If you installed @sharyn/util.trycatch
import tryCatch from '@sharyn/util.trycatch' // smaller size, better for client bundles

// If you installed @sharyn/util
import tryCatch from '@sharyn/util/tryCatch' // smaller size, better for client bundles
import { tryCatch } from '@sharyn/util' // more convenient in Node environments

// If you installed sharyn
import tryCatch from 'sharyn/util/tryCatch' // smaller size, better for client bundles
import { tryCatch } from 'sharyn/util' // more convenient in Node environments

This package is part of Sharyn, a collection of utilities and helpers.