using-try-catch
v1.0.0
Published
Simplify the use of try-catch
Readme
A tiny utility that simplifies try-catch handling in JavaScript/TypeScript. No more repetitive try-catch blocks for every async operation.
Why?
Handling errors with async/await often leads to verbose code:
const fetchData = async () => {
let data;
let error;
try {
data = await api.get('/user');
} catch (err) {
error = err;
}
if (error) return handleError(error);
return processData(data);
};Quick Start
npm install using-try-catchimport usingTryCatch from 'using-try-catch';
const fetchData = async () => {
const { data, error } = await usingTryCatch(api.get('/user'));
if (error) return handleError(error);
return processData(data);
};That's it! Returns { data, error } - always.
Features
- Zero dependencies - Ultra lightweight
- TypeScript support - Fully typed out of the box
- Universal - Works in Node.js and browsers
- Flexible - Handles single or multiple promises
Usage
Single Promise
const { data, error } = await usingTryCatch(fetchUser());
if (error) {
console.log('Failed:', error.message);
return;
}
console.log('User:', data.name);Multiple Promises (Parallel)
const { data, error } = await usingTryCatch([
fetchUser(),
fetchPosts(),
fetchComments()
]);
if (error) {
console.log('One or more requests failed');
return;
}
const [user, posts, comments] = data;API
usingTryCatch<T>(promise: Promise<T> | Promise<T>[]): Promise<{
data: T | T[] | null;
error: unknown;
}>- Returns an object with
dataanderrorproperties errorisnullon success, unknown on failure- Works with single promises or arrays of promises
TypeScript
Fully typed out of the box:
import usingTryCatch from 'using-try-catch';
const { data, error } = await usingTryCatch(fetchUser());
// data is typed as User | User[] | null
// error is typed as unknownRequirements
- Node.js >= 18
Browser
Load via CDN:
<script src="https://cdn.jsdelivr.net/npm/using-try-catch/dist/esm/using-try-catch.js"></script>
<script>
const { data, error } = await usingTryCatch(fetch('/api/data'));
</script>Contributing
Contributions are welcome! Please see CONTRIBUTING.md for details.
License
MIT - See LICENSE for details.
