JavaScript Interview Question #84

How do you handle errors with async/await?

Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate

Quick Interview Answer

Use try/catch around awaited operations when the function should handle a rejection locally. The catch block receives the thrown rejection reason, which is commonly an Error object.

Detailed Explanation

Use try/catch around awaited operations when the function should handle a rejection locally. The catch block receives the thrown rejection reason, which is commonly an Error object.

Alternatively, allow the async function's returned Promise to reject and handle the error at a higher application boundary. Avoid silently swallowing errors unless the failure is genuinely expected and intentionally handled.

Code Example

async function loadProducts() {
    try {
        const response = await fetch("/api/products");

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }

        return await response.json();
    } catch (error) {
        console.error("Could not load products:", error);
        throw error;
    }
}