How do I handle errors with try/catch around await?
Written by Jatin Thacker, Automation Architect · Updated
await inside the try block: if the awaited Promise rejects, await throws the error there and your catch block receives it. A Promise that is not awaited inside the try rejects later, after the try has finished, and the catch never sees it.This answer is one piece of Chapter 6: Async and Await.
- Error Handling & Debugging
- Callbacks & Promises
- Async/Await Mastery
- Practice and interview questions: Asynchronous JavaScript & Modern ES6+
try/catch catches errors thrown while the try block runs. With async code, await is what turns a rejected Promise into a thrown error at that line, so the await has to be inside the block.
In the example, placeOrder(120) rejects because 120 is above the quantity limit of 99, the same limit the order edit form uses. Because the call is awaited inside try, the error lands in catch, which prints the message. finally runs whether or not anything failed, which makes it the place for cleanup such as deleting test data.
noAwait() shows the mistake. It writes return placeOrder(120) inside a try, with no await. The try block finishes as soon as it has handed back the Promise, so its catch never runs, and the error escapes to the caller. Writing return await placeOrder(120) would keep the error inside the function.
In a Playwright test, think before catching at all. An uncaught error is how a test fails, and swallowing one turns a real failure into a pass. Catch when you need to add context, clean up, or handle a step that is genuinely optional, then rethrow anything you did not expect.
async function placeOrder(qty) {
await new Promise((r) => setTimeout(r, 50));
if (qty > 99) throw new Error(`Quantity ${qty} is above the limit of 99`);
return 'ORD-4147';
}
try {
const id = await placeOrder(120);
console.log('placed', id);
} catch (err) {
console.log('caught:', err.message);
} finally {
console.log('cleanup runs either way');
}
async function noAwait() {
try {
return placeOrder(120);
} catch {
console.log('never printed');
}
}
noAwait().catch((err) => console.log('escaped the try:', err.message));caught: Quantity 120 is above the limit of 99 cleanup runs either way escaped the try: Quantity 120 is above the limit of 99
try { const id = await createOrder(); } catch (err) { ... }, createOrder() rejects. Where does the error go?Practised in the full course: the drill The catch that never fires.
See the chapterRelated questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free