In this tutorial, you will learn how to handle errors in Node.js applications using various techniques like `try/catch`, error objects, and Express error-handling middleware.
Node.js Error Handling
1. Handling Synchronous Errors
In Node.js, you can catch synchronous errors using `try/catch` blocks. Here's an example:
try {
const result = riskyFunction();
} catch (error) {
console.error('An error occurred:', error.message);
}
In this example, if `riskyFunction` throws an error, it is caught and logged.
2. Handling Asynchronous Errors
For asynchronous code, errors can be handled using callback functions, promises, or `async/await` with `try/catch`:
async function fetchData() {
try {
const data = await fetch('https://api.example.com/data');
const jsonData = await data.json();
console.log(jsonData);
} catch (error) {
console.error('Error fetching data:', error.message);
}
}
In the above example, errors are caught when the `fetch` call or `await` throws an error.
3. Express Error Handling Middleware
In Express applications, errors are often handled using middleware. The following example shows how to define an error-handling middleware:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
This middleware catches all errors in your Express app and sends a generic 500 status code response.
4. Conclusion
Error handling is crucial in any Node.js application. You should ensure that both synchronous and asynchronous errors are properly handled to avoid crashing the app and provide meaningful feedback to users.