Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Handling Errors in Express | Section
Building APIs with Express.js

bookHandling 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?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 15

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 15
some-alt