When you're building applications with Node.js, it's super important to handle errors well. Here are some simple ways to do this using the HTTP module and the Express.js framework:
Using Middleware in Express.js:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Try-Catch Blocks:
app.get('/', async (req, res) => {
try {
// code that might throw an error
} catch (error) {
res.status(500).send('Error occurred!');
}
});
Global Error Handling:
app.use((req, res) => {
res.status(404).send('Sorry, that route doesn’t exist!');
});
By using these tips, you can make your Node.js server more reliable. This means it could crash 50% less often!
When you're building applications with Node.js, it's super important to handle errors well. Here are some simple ways to do this using the HTTP module and the Express.js framework:
Using Middleware in Express.js:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Try-Catch Blocks:
app.get('/', async (req, res) => {
try {
// code that might throw an error
} catch (error) {
res.status(500).send('Error occurred!');
}
});
Global Error Handling:
app.use((req, res) => {
res.status(404).send('Sorry, that route doesn’t exist!');
});
By using these tips, you can make your Node.js server more reliable. This means it could crash 50% less often!