In Node.js, you can use try and catch blocks to handle errors that might occur while running your code. The try block contains the code that might throw an error, and the catch block contains the code to handle that error. Here’s an example:
try {
// Code that might throw an error
const result = 1 / 0;
console.log(result);
} catch (error) {
// Code to handle the error
console.error('An error occurred:', error);
}
In this example, the code in the try block attempts to divide 1 by 0, which will throw a “Division by zero” error. The catch block catches this error and logs a message to the console.
You can also use try and catch blocks with asynchronous code that uses Promises. Here’s an example:
async function fetchData() {
try {
const response = await fetch('https://example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('An error occurred:', error);
}
}
fetchData();
In this example, the fetchData function uses the fetch API to retrieve data from an API endpoint. The code in the try block uses the await keyword to wait for the response and data to be returned from the API. If an error occurs, the catch block logs a message to the console.
Using try and catch blocks can help you handle errors more gracefully and prevent your Node.js application from crashing.