1.0.7 • Published 5 years ago

@sharyn/util.trycatch v1.0.7

Weekly downloads
11
License
MIT
Repository
github
Last release
5 years ago

🌹 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
1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago