Error & Exception Handling: try-catch-finally, Custom Error & Async Await Try/Catch
1Concept
JavaScript handles errors via try-catch-finally. Errors inherit from Error (TypeError, RangeError, SyntaxError). Asynchronous Promise rejections in async/await functions are caught seamlessly with standard try/catch.
2Architecture Diagram
try {
await fetchApi();
} catch (err) {
// Catches both synchronous exceptions AND async Promise rejections!
}3Code Example
Stage 0 Language Foundations
class ApiError extends Error {
constructor(message, statusCode) {
super(message);
this.name = "ApiError";
this.statusCode = statusCode;
}
}
async function simulateApiCall(success) {
if (!success) {
throw new ApiError("Failed to fetch user credentials.", 401);
}
return { user: "Authenticated" };
}
async function main() {
try {
console.log("Attempting API call...");
await simulateApiCall(false);
} catch (err) {
if (err instanceof ApiError) {
console.error(`[${err.name} ${err.statusCode}] ${err.message}`);
} else {
console.error(`[Unknown Error]`, err);
}
} finally {
console.log("API request lifecycle completed.");
}
}
main();4Expected Output
Attempting API call... [ApiError 401] Failed to fetch user credentials. API request lifecycle completed.
5Key Takeaways
- ✓Always throw instances of Error (or custom subclasses), never raw strings.
- ✓async functions return Promises and must be wrapped in try/catch or .catch().
- ✓Listen to process.on('unhandledRejection') in Node.js backend servers.