Skip to content

CasperEngl/try-catch

Repository files navigation

Try Catch

Version Documentation Maintenance License: MIT Twitter: casperengl

Functional library to try-catch code that accepts functions and promises

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 [email protected]

🤝 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 [email protected].
This project is MIT licensed.


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