Ton Snoei

How to use a try catch with a promise in javascript?

Published 2 years ago1 min read
Promise Thumb

You can use a try-catch block with a promise in JavaScript by chaining a .catch() method onto
the promise. The catch() method receives the rejection reason as an argument and it allows you to
handle the exception.

Here's an example:

fetch('https://example.com')
    .then(response => response.text())
    .then(data => console.log(data))
    .catch(error => console.log('Error:', error))

Alternatively, you can also use async/await syntax to handle the promise and catch the exception if it occurs.

async function getData() {
    try {
        const response = await fetch('http://example.com');
        const data = await response.text();
        console.log(data);
    } catch (error) {
        console.log('Error:', error);
    }
}

await getData();

You also can wrap your entire async/await function with try/catch block

try {
    const data = await getData();
    console.log(data);
} catch (error) {
    console.log('Error:', error);
}

This way, any errors that occur in the promise will be caught and handled by the catch() method,
or the catch block of the try/catch statement.