Module 56 : Async / Await Error
Handling in Async Code.
1. Introduction to Async/Await
What is async/await?
● Introduced in ES2017 (ES8),
async/await is syntactic sugar
over Promises that makes
asynchronous code look and
behave like synchronous code.
● Makes it easier to write and
manage async flows, especially
with error handling.
Traditional Promises vs
Async/Await
✅ Promise Version
fetch('https:/ api.example.com/da
ta') .then(response =>
response.json()) .then(data =>
console.log(data)) .catch(error =>
console.error('Error:', error));
✅ Async/Await Version
async function fetchData() { try {
const response = await
fetch('https:/ api.example.com/da
ta'); const data = await
response.json(); console.log(data);
} catch (error) {
console.error('Error:', error); } }
fetchData();
✔️ Cleaner, more readable, and
structured for error handling.
2. Error Handling in Async/Await
Structure
async function yourFunction() {
try { / Code that may throw an
error } catch (error) { / Error
handling logic } finally { /
Optional: cleanup, runs whether
error occurred or not } }
✅ Example
async function
getUserData(userId) { try { const
response = await
fetch(`https:/ api.example.com/u
sers/${userId}`); if (!response.ok) {
throw new Error(`HTTP Error!
Status: ${response.status}`); }
const data = await
response.json(); console.log("User
Data:"
, data); } catch (error) {
console.error("Failed to fetch user
data:"
, error.message); } finally {
console.log("Fetch attempt
complete.
"); } }
3. Explanation
try...catch
● Catches any errors during the
await of Promises.
● Can handle network errors,
API failure, JSON parse errors,
or even coding bugs.
throw
● Used to throw custom errors
for specific conditions (e.g.,
response not ok).
✅ finally
● Always executes whether an
error occurred or not — used
for cleanup or logs.
4. Exercises
Exercise 1: Basic API Fetch with
Error Handling
Create a function getPostById(id)
that:
● Fetches a post from
https:/ jsonplaceholder.typico
de.com/posts/{id}
● Logs post data.
● Catches and logs errors.
async function getPostById(id) {
try { const response = await
fetch(`https:/ jsonplaceholder.typ
icode.com/posts/${id}`); if
(!response.ok) { throw new
Error(`Post not found with status
${response.status}`); } const post =
await response.json();
console.log("Post:", post); } catch
(error) { console.error("Error
fetching post:"
, error.message); } }
getPostById(2); / Try with valid
and invalid IDs
✅ learn: Fetch API, status check,
try/catch, custom error
messages.
Exercise 2: Handling Delayed
Operations with Timeout
function delay(ms) { return new
Promise(resolve =>
setTimeout(resolve, ms)); } async
function delayedGreeting(name) {
try { await delay(2000); if (!name)
throw new Error("Name is
required!"); console.log(`Hello,
${name}!`); } catch (error) {
console.error("Greeting failed:",
error.message); }
delayedGreeting("Rehana");
delayedGreeting(); / Test
missing name
✅ learn: Delays, promise-based
timeout, input validation.
Exercise 3: Chained Async
Functions with Nested Try/Catch
async function getUser(userId) {
const response = await
fetch(`https:/ jsonplaceholder.typ
icode.com/users/${userId}`); if
(!response.ok) throw new
Error("User not found"); return
response.json(); } async function
displayUserName(userId) { try {
const user = await
getUser(userId);
console.log(`Username:
${user.username}`); } catch (error)
{ console.error("Error:",
error.message); } }
displayUserName(1);
displayUserName(9999); /
Triggers error
✅ learn: Composing async
functions, propagating and
catching errors.
5. Tips and Structure
Segment Duration Activity
Introducti
on to
async/aw
ait
10 min
Theory
with basic
example
Error
Handling
Theory
10 min
try/catch,
finally,
throw
Hands-on
Demos
20 min
Live-codin
g
Exercises
1–3
Practice 15 min
Group
activity or
solo tasks
Q&A and
Recap
5 min
Summariz
e concepts
Suggestions
● Encourage to break code on
purpose to see how errors
propagate.
● Ask to customize the error
messages.
● Simulate failure cases by
using invalid URLs or
conditions.
6. Research & Developer
● Always wrap await calls in
try...catch.
● Validate user input before
awaiting.
● Return meaningful messages
and avoid silent errors.
● Create error utility functions
for reuse.
● Log both error messages and
stack traces in apps.
Developer Quotes:
“Code should fail loudly in
development, but fail gracefully
in production.
”
— Nicholas C. Zakas
Example Error Utility
function handleError(error,
context = "") {
console.error(`[${context}] Error:`,
error.message); }
7. Async/Await with .catch()
(less preferred)
async function fetchData() { const
data = await
fetch('https:/ api.example.com')
.then(res => res.json()) .catch(error
=> { console.error("Error inside
chain:"
, error.message); }); }
✅ Avoid mixing await and
.then().catch() unless you
understand flow clearly.
Review
1. if an error is thrown inside
an async function without
try...catch.
2. throw a custom error in
async/await.
3. finally useful?
4. Write a function that
delay.
execution and throws if
an.
argument is missing.
5. Convert this .then() based
code to async/await.
Summary
Concept Notes
async
Marks a
function as
asynchronous
await
Waits for a
Promise to
resolve
try...catch
Catches errors
inside async
blocks
throw
Creates custom
error messages
finally
Optional,
always runs
cleanup logic
Assignment
Build a small app:
● Input: User ID
● Output: Display user details
● Use: Async/await with error
handling for invalid user, API
errors, and input validation
No comments:
Post a Comment