Handling Errors in Express
Swipe to show menu
Errors can happen when something goes wrong, such as invalid input or missing data.
In Express, you can send error responses using the response object.
app.get('/users/:id', (req, res) => {
const id = Number(req.params.id);
const user = users.find(u => u.id === id);
if (!user) {
return res.status(404).send('user not found');
}
res.json(user);
});
Here, if the user is not found, the server sends a response with a status code and a message.
Status codes help indicate what happened:
- 200: success;
- 404: resource not found;
- 500: server error.
Handling errors properly makes your API more predictable and easier to use.
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 15
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Section 1. Chapter 15