good-try
Tries to execute sync/async function, returns a specified default value if the function throws.

Install
npm install good-try
Usage
import goodTry from 'good-try'
const value = goodTry(() => JSON.parse(todos), [])
const todos = await goodTry(fetchTodos(), [])
const todos = await goodTry(fetchTodos(), (err) => {
sentToErrorTrackingService(err)
return []
})
API
First parameter accepts:
- synchronous function
goodTry(() => JSON.parse(value))
- asynchronous function / Promise
- synchronous function that returns a promise
Second parameter accepts:
- any value that will be returned if the first parameter throws
- a callback that receives
err
as first parameter (the return value of the callback is returned if the first parameter throws)
If you use TypeScript, the types are well defined and won't let you make a mistake.