What is the main reason to use try-catch blocks in Node.js code?
Think about what happens when an error occurs during program execution.
Try-catch blocks help catch errors that happen while the program runs, so the program can handle them gracefully instead of crashing.
What happens when a promise in Node.js is rejected but there is no catch handler?
Promise.reject(new Error('Failed')).then(() => console.log('Success'));
Think about what Node.js does when a promise rejection is not handled.
Node.js warns about unhandled promise rejections and depending on the version and settings, it may crash the process to avoid silent failures.
What is wrong with this Node.js code snippet regarding error handling?
const fs = require('fs'); fs.readFile('file.txt', (err, data) => { console.log(data.toString()); });
Consider what happens if err is not null.
If err is not checked, the code might try to use data which could be undefined, causing a runtime error.
Which option correctly handles errors in an async function using try-catch in Node.js?
async function fetchData() {
// fetch data code
}Remember that await must be inside try to catch errors properly.
Option A correctly uses await inside a try block and catches errors in catch. Option A mixes await and catch incorrectly. Option A misses await. Option A has no error handling.
Consider this Node.js Express server code snippet. What happens if next(error) is called but no error-handling middleware is defined?
const express = require('express'); const app = express(); app.get('/', (req, res, next) => { const error = new Error('Something went wrong'); next(error); }); app.listen(3000);
Express has a built-in error handler that handles errors passed to next(error) if no custom one is defined.
Express has a built-in error handler that responds with a default 500 Internal Server Error page when no custom error-handling middleware is defined.