Hone

Lessons · TypeScript · catching a promise

Catching a rejection

A promise that rejects with nobody listening is an unhandled rejection: often silent, sometimes fatal. Attach .catch, or await inside try/catch.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A network call that fails at 2am must be seen somewhere. Unhandled rejections are how a page quietly stops working with a blank spot where the data should be.

How to think about it

Every promise chain ends in .catch; every await that can fail sits in a try. Report the error where a person will see it, then decide whether to retry or degrade.

Worked example

async function risky() { throw new Error("bad"); }
Rejects.
risky().catch(e => console.log("caught", e.message));
caught bad: without the catch, the rejection is unhandled.
async function safe() { try { await risky(); } catch (e) { return "handled"; } }
await rethrows the rejection, so try/catch works.
safe().then(console.log);
handled.

Your turn

Report any failure of the fetch.

fetchData().(err => report(err));

The trap

.then(ok, fail) does not catch errors thrown inside ok. Put .catch after the then, where it covers both.

Next in TypeScript

Every TypeScript lesson on one page

Practise catching a promise on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.