@casperengl/try-catch
TypeScript icon, indicating that this package has built-in type declarations

1.9.0 • Public • Published

Welcome to @casperengl/try-catch 👋

Version GitHub Action Documentation Maintenance License: MIT Twitter: casperengl

Package to trycatch code that accepts functions and promises

🏠 Homepage

🔎 Example (Inspect page for source)

Install

npm install @casperengl/try-catch

# or
yarn add @casperengl/try-catch

Usage

Bundler (Webpack, Rollup, etc.)

import { tryCatch } from '@casperengl/try-catch';

// Or default import
import tryCatch from '@casperengl/try-catch';

Browser (ESM)

Notice type="module" is required to use import statements in the browser.

<script type="module">
  import { tryCatch } from 'https://cdn.skypack.dev/@casperengl/try-catch';
  // Or default import
  // import tryCatch from 'https://cdn.skypack.dev/@casperengl/try-catch';

  const apiCall = async () => {
    const promise = fetch('https://reqres.in/api/users/1').then((response) => response.json());
    const [error, result] = await tryCatch(promise);

    console.log(error, result); // null, {data: {…}, support: {…}}
  };

  apiCall();
</script>

Function

(async () => {
  // success
  const fn = () => 'success';

  const [error, result] = await tryCatch(fn);

  console.log([error, result]); // [null, 'success']
})();

(async () => {
  // error
  const fn = () => {
    if (true) {
      throw new Error('An error occurred');
    }

    return 'success';
  };

  const [error, result] = await tryCatch(fn);

  console.log([error, result]); // [[Error: An error occurred], undefined]
})();

Promise

(async () => {
  // success
  const promise = () => Promise.resolve('success');

  const [error, result] = await tryCatch(promise);

  console.log([error, result]); // [null, 'success']
})();

(async () => {
  // error
  const promise = () => Promise.reject('An error occurred');

  const [error, result] = await tryCatch(promise);

  console.log([error, result]); // [[Error: An error occurred], undefined]
})();

Axios

Or the likes of Axios

(async () => {
  // Do not unwrap the response with `await`
  const promise = axios.get('https://reqres.in/api/users/1');

  const [error, result] = await tryCatch(promise);

  console.log([error, result]); // [null, { ..., data: { data: { first_name: 'George', last_name: 'Bluth' } } }]
})();

Run tests

npm run test

Author

👤 Casper Engelmann me@casperengelmann.com

🤝 Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

Show your support

Give a ⭐️ if this project helped you!

📝 License

Copyright © 2019 Casper Engelmann me@casperengelmann.com.
This project is MIT licensed.


This README was generated with ❤️ by readme-md-generator

Package Sidebar

Install

npm i @casperengl/try-catch

Weekly Downloads

1

Version

1.9.0

License

MIT

Unpacked Size

40.3 kB

Total Files

30

Last publish

Collaborators

  • casperengl