Loading...
Loading...

Node.js Error Handling

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.

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.

0 Interaction
2.3K Views
Views
29 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home