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

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:

1fetch('https://example.com')
2    .then(response => response.text())
3    .then(data => console.log(data))
4    .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.

 1async function getData() {
 2    try {
 3        const response = await fetch('http://example.com');
 4        const data = await response.text();
 5        console.log(data);
 6    } catch (error) {
 7        console.log('Error:', error);
 8    }
 9}
10
11await getData();

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

1try {
2    const data = await getData();
3    console.log(data);
4} catch (error) {
5    console.log('Error:', error);
6}

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.