Custom Error Handling with http-proxy-middleware in Express.js

124 Views Asked by At

I am trying to implement custom error handling for a proxy server in an Express.js application using http-proxy-middleware. The goal is to display a custom error page when the target domain returns a 404 error. Here's the simplified code structure:

const express = require('express');
const http = require('http');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');

const app = express();
const port = 3000;

// Configure proxy middleware for a single domain
const proxyOptions = {
  target: 'http://example.com',
  changeOrigin: true,
  pathRewrite: {
    '^/proxy': '',
  },
};

const proxy = createProxyMiddleware('/proxy', proxyOptions);

// Use the middleware
app.use('/proxy', proxy);

// Custom error handling for 404 errors
app.use((err, req, res, next) => {
  if (err.status === 404) {
    // Serve custom 404 error page
    res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
  } else {
    // Handle other errors
    res.status(err.status || 500);
    res.send({
      message: err.message,
      error: err,
    });
  }
});

// Start the server
const server = http.createServer(app);

server.listen(port, () => {
  console.log(`Proxy server listening on port ${port}`);
});

However, the custom error page is not being served when a 404 error occurs on the target domain (example.com). Instead, the default error message from the target domain is displayed. I have verified that the custom error page (404.html) exists in the 'public' directory.

What am I missing in my implementation, and how can I ensure that the custom error page is served for 404 errors?

1

There are 1 best solutions below

1
Nazrul Chowdhury On

You are trying to handle errors globally for your Express application, but the issue is that the createProxyMiddleware does not propagate errors in a way that the global error handler can catch them but rather sends them directly to the client without passing through your custom error handling middleware.To handle errors specific to the proxy middleware, you can try setting the onError option in your proxyOptions,

const proxyOptions = {
  target: 'http://example.com',
  changeOrigin: true,
  pathRewrite: {
    '^/proxy': '',
  },
  onError: (err, req, res) => {
    if (res.statusCode === 404) {
      // Serve custom 404 error page ...
      res.status(404).sendFile(path.join(__dirname, 'public', '404.html'))
    } else {
      // Handle other proxy errors ...
      res.status(500).send({
        message: 'Proxy Error',
        error: err,
      })
    }
  },
}