Created
September 4, 2023 08:53
-
-
Save unes/47d0769a374f9a7b8214f58d5a45e7d8 to your computer and use it in GitHub Desktop.
Error Handling - Express.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
// Route handler | |
app.get('/users/:id', (req, res, next) => { | |
const userId = req.params.id; | |
// Simulating an error when user is not found | |
if (!getUserById(userId)) { | |
const error = new Error('User not found'); | |
error.statusCode = 404; | |
next(error); | |
} else { | |
// If user is found, send the user data as response | |
const user = getUserById(userId); | |
res.json(user); | |
} | |
}); | |
// Error handling middleware | |
app.use((err, req, res, next) => { | |
// Default error status code | |
const statusCode = err.statusCode || 500; | |
// Default error message | |
const message = err.message || 'Internal Server Error'; | |
// Sending the error response | |
res.status(statusCode).json({ error: message }); | |
}); | |
// Starting the server | |
app.listen(3000, () => { | |
console.log('Server is listening on port 3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment