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

Overview

good-try

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

Gzipped Size Build Status

Why

Why not nice-try with it's 70+ million downloads per month?

  • good-try supports async functions.
  • good-try supports an optional default value.
  • good-try allows you to capture the thrown error.
  • good-try is written in TypeScript and the types are in a way to reduce developer errors. For example, I sometimes incorrectly type goodTry(readFileSync()), but the types don't allow this.
  • good-try has a friend β€” settle-it.
  • I aim for high-quality with my open-source principles.

Install

npm install good-try

Usage

import goodTry from 'good-try'

// tries to parse todos, returns empty array if it fails
const value = goodTry(() => JSON.parse(todos), [])

// fetch todos, on error, fallback to empty array
const todos = await goodTry(fetchTodos(), [])

// fetch todos, fallback to empty array, send error to your error tracking service
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.

Related

  • settle-it – Like Promise.allSettled() but for sync and async functions. Similarly to good-try it handles sync/async functions that throw an error. However, it returns an object so you know if and what error was thrown.
You might also like...

A simple website that returns a random advice.

A simple website that returns a random advice.

Advice Preview πŸš€ Technologies This project was developed with the following technologies: HTML CSS JavaScript API's Advice Slip JSON API πŸ’» Project A

Sep 2, 2022

Given an object and a property, replaces a property descriptor (or deletes it), and returns a thunk to restore it.

Given an object and a property, replaces a property descriptor (or deletes it), and returns a thunk to restore it.

Given an object and a property, replaces a property descriptor (or deletes it), and returns a thunk to restore it.

Apr 20, 2022

A request library that returns promises, inspired by request

then-request A request library that returns promises and supports both browsers and node.js Installation npm install then-request Usage request(metho

Nov 29, 2022

Fix for Object.hasOwnProperty, which normally just returns a boolean, which is not good when you care about strong typing.

Fix for Object.hasOwnProperty, which normally just returns a boolean, which is not good when you care about strong typing.

Welcome to ts-has-own-property πŸ‘‹ Fix for Object.hasOwnProperty, which normally just returns a boolean, which is not good when you care about strong t

Jul 4, 2022

Fix for Object.keys, which normally just returns an array of strings, which is not good when you care about strong typing

Fix for Object.keys, which normally just returns an array of strings, which is not good when you care about strong typing

Welcome to ts-object-keys πŸ‘‹ Fix for Object.keys, which normally just returns an array of strings, which is not good when you care about strong typing

Jul 4, 2022

Execute obsidian commands with short key sequences. For example, 'tp' for 'Toggle Preview' and 'tb' for 'Toggle Sidebar'. Easier to remember.

Execute obsidian commands with short key sequences. For example, 'tp' for 'Toggle Preview' and 'tb' for 'Toggle Sidebar'. Easier to remember.

Key Sequence Shortcut Key Sequence Shortcut is an obsidian plugin, allow binding key sequences to an obsidian command. For example If we assume "t" st

Dec 26, 2022

This is a project that is used to execute python codes in the web page. You can install and use it in django projects, You can do any operations that can be performed in python shell with this package.

Django execute code This is a project that is used to execute python codes in the web page. You can install and use it in django projects, You can do

Nov 12, 2022

The project is a To-Do list project to help plan daily, weekly or monthly activity. I used Html, CSS and JavaScript Technology to execute the project.

HEAD To Do List This project is geared towards applying acguired skills for development of my porfolio through the following practices: Create

Dec 19, 2022

Basic Implementation of a Contract Wallet in Solidity. The owner can transfer Ether/ERC20 and execute transactions via low-level calls.

Contract Wallet Basic Implementation of a Contract Wallet in Solidity. The owner can transfer Ether/ERC20 and execute transactions via low-level calls

Jun 18, 2022
Comments
  • Golang style result

    Golang style result

    I liked your library but made some changes so it returns a result tuple, similar to Golang style of dealing with exceptions. See if you like, if not I will rename my implementation, mentioning your project.

    opened by thelinuxlich 3
Releases(v1.0.2)
Owner
Antonio Stoilkov
Cooling off my perfectionism doing open-source. Founder of @notaapp – pro notes app for your local Markdown files.
Antonio Stoilkov
Tiny JavaScript library (1kB) by CurrencyRate.today, providing simple way and advanced number, money and currency formatting and removes all formatting/cruft and returns the raw float value.

Zero dependency tiny JavaScript library (1kB bytes) by CurrencyRate.today, providing simple way and advanced number, money and currency formatting and removes all formatting/cruft and returns the raw float value.

Yurii De 11 Nov 8, 2022
A workshop about JavaScript iteration protocols: iterator, iterable, async iterator, async iterable

JavaScript Iteration protocol workshop A workshop about JavaScript iteration protocols: iterator, iterable, async iterator, async iterable by @loige.

Luciano Mammino 96 Dec 20, 2022
A small web app that tries to imitate the desktop web version of amazon site, you can add items to the basket, delete them, and have your user authentication feature thanks to Firebase.

Features Here's the feature's included in this project ??‍??‍??‍?? Login Page ?? Products Page ?? Cart and Checkout Page ?? Sign up function with Goog

Murad Rahmanzada 16 Aug 22, 2022
When a person that doesn't know how to create a programming language tries to create a programming language

Kochanowski Online SprΓ³buj Kochanowskiego bez konfiguracji projektu! https://mmusielik.xyz/projects/kochanowski Instalacja StwΓ³rz nowy projekt przez n

Maciej Musielik 18 Dec 4, 2022
A JavaScript Library that allows you to execute function when a certain element gets added to the document

wait-for-it.js A JavaScript Library that allows you to execute function when a certain element gets added to the document Getting Started If you want

Muhammad Tayyab Sheikh 12 Apr 26, 2022
CLI utility that parses argv, loads your specified file, and passes the parsed argv into your file's exported function. Supports ESM/TypeScript/etc out of the box.

cleffa CLI tool that: Parses argv into an object (of command-line flags) and an array of positional arguments Loads a function from the specified file

Lily Scott 9 Mar 6, 2022
βš–οΈ Limit an async function's concurrency with ease!

limit-concur Limit an async function's concurrency with ease! Install $ npm i limit-concur Usage import got from 'got' import limitConcur from 'limit-

Tomer Aberbach 19 Apr 8, 2022
This simple project, show how work with async Fetch, function component and class component

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

DaliyaAsel 2 Feb 17, 2022
Very tiny function that checks if an object/array/value is shaped like another, with TypeScript type refining.

@suchipi/has-shape Very tiny (~200B before minification/compression) function that checks if an object/array/value is shaped like another, with TypeSc

Lily Skye 7 Aug 13, 2022
I forgot about el.outerHTML so I made this, it takes a DOM element and returns its html as string

htmlToString Convert html/DOM element to string Works with rendered and virtual DOM Installation npm install htmltostring Or using CDN <script src="ht

Shuvo 4 Jul 22, 2022