Functional library to try-catch code that accepts functions and promises
🏠 Homepage
npm install @casperengl/try-catch
# or
yarn add @casperengl/try-catch
import { tryCatch } from '@casperengl/try-catch';
// Or default import
import tryCatch from '@casperengl/try-catch';
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>
(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]
})();
(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]
})();
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' } } }]
})();
npm run test
👤 Casper Engelmann [email protected]
- Website: https://casperengelmann.com/
- Twitter: @casperengl
- Github: @CasperEngl
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Give a ⭐️ if this project helped you!
Copyright © 2019 Casper Engelmann [email protected].
This project is MIT licensed.
This README was generated with ❤️ by readme-md-generator