,

Setting up Global Error and 404 Handlers 🛠

Posted by


Setting up a global error handler and 404 handler in your application is essential for handling errors and providing a better user experience. In this tutorial, we will go through the process of setting up both handlers in a Node.js application using Express.

Step 1: Create a new Express application
First, create a new Node.js application using the following command:

npm init -y

Next, install Express using the following command:

npm install express

Create a new file named app.js and open it in your favorite code editor.

Step 2: Initialize your Express application
In your app.js file, require Express and initialize your application. Add the following code:

const express = require('express');
const app = express();

// Add other middleware and routes here

Step 3: Set up the global error handler
To set up a global error handler in your Express application, add the following code after initializing your app:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

In the code above, we defined a middleware function that takes four parameters (err, req, res, next). Inside this function, we log the error stack trace and send a generic error message with a status code of 500.

Step 4: Set up the 404 handler
To set up a 404 handler in your Express application, add the following code at the end of your app.js file:

app.use((req, res) => {
  res.status(404).send('Page not found');
});

In the code above, we defined a middleware function that handles all requests that do not match any other route. We set the status code to 404 and send a message indicating that the page was not found.

Step 5: Test your error handler setup
To test your error handler setup, create a route that throws an error. Add the following code to your app.js file:

app.get('/error', (req, res, next) => {
  next(new Error('This is a test error'));
});

Start your Express server using the following command:

node app.js

Navigate to http://localhost:3000/error in your browser to trigger the error route and see the global error handler in action.

To test the 404 handler, navigate to a non-existent route such as http://localhost:3000/nonexistent and see the message "Page not found" displayed.

Congratulations! You have successfully set up a global error handler and 404 handler in your Express application. This will help you handle errors and provide a better user experience for your application.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x