Lesson 27 of 30

Error Handling

Chapter 27

Error Handling

Learn how to handle errors safely in Node.js and Express applications.

Theory

Error handling is important for building reliable Node.js applications. Errors can occur because of: • Invalid input • Database failures • Network problems • Missing resources • Programming mistakes Express supports error-handling middleware with four parameters: (err, req, res, next) Applications should return useful error responses without exposing sensitive internal information.

Example

Node.js Example
app.use((err, req, res, next) => {
  console.error(err);

  res.status(500).json({
    message: "Internal Server Error"
  });
});

Output

The server returns a controlled error response.

Practice

Create Express error-handling middleware for a REST API.

Interview Questions

1.

Why is error handling important?

2.

What is Express error-handling middleware?

3.

What status code is commonly used for unexpected server errors?

Quick Quiz

Which option best matches this chapter?

A.Error-handling middleware
B.CSS middleware
C.Database indexing
D.HTML rendering

Answer: Error-handling middleware