Back to Snippets
CODE
Async/Await Error Handler
Description
Simplifies async/await error handling without try/catch blocks, returns [error, result] tuple
Code
/**
* Async/await error handler
* @param promise Promise to execute
* @returns Tuple [error, result]
*/
async function asyncHandler<T>(promise: Promise<T>): Promise<[Error | null, T | null]> {
try {
const result = await promise;
return [null, result];
} catch (error) {
return [error as Error, null];
}
}
// Usage Example
const fetchData = () => fetch('https://api.example.com/data').then(res => res.json());
// Without try/catch
const [error, data] = await asyncHandler(fetchData());
if (error) {
console.error('Fetch failed:', error);
} else {
console.log('Data:', data);
}Usage
Reduces try/catch boilerplate in async functions, makes error handling more declarative and readable