chimurai / http-proxy-middleware

:zap: The one-liner node.js http-proxy middleware for connect, express, next.js and more
MIT License
10.7k stars 834 forks source link

Errors in router are not propagated to onError handler #793

Closed itaied246 closed 2 years ago

itaied246 commented 2 years ago

Checks

Describe the bug (be clear and concise)

I have set the proxy with custom router logic:

onError: handleProxyErrors,
router: async (req) => { ... }

When an error inside the router logic happens, the onError doesn't receive it and the client receive the error.

Step-by-step reproduction instructions

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

const app = express();

app.use(
  createProxyMiddleware({
    router: (req) => {
      throw new Error("BOOM!")
    },
    onError: (err, req, res, target) => {
      console.log(err)
      res.writeHead(500, {
        "Content-Type": "text/plain",
      });
      res.end("Internal server error.");
    }
  })
);

app.listen(8080, () => {
  console.log("🚀  server started");
  console.log(`↗️  example: "curl https://44oc1.sse.codesandbox.io/json"`);
});

Expected behavior (be clear and concise)

The error handler should receive and handle the errors happening in the router

How is http-proxy-middleware used in your project?

yarn why v1.23.0-20220130.1630
warning ../../../package.json: No license field
[1/4] Why do we have the module "http-proxy-middleware"...?
[2/4] Initialising dependency graph...
[3/4] Finding dependency...
[4/4] Calculating file sizes...
=> Found "http-proxy-middleware@2.0.6"
info Has been hoisted to "http-proxy-middleware"
info This module exists because it's specified in "dependencies".
info Disk size without dependencies: "156KB"
info Disk size with unique dependencies: "2.32MB"
info Disk size with transitive dependencies: "4.45MB"
info Number of shared dependencies: 8
Done in 0.24s.

### What http-proxy-middleware configuration are you using?

```typescript
app.use(
    "/",
    createProxyMiddleware({
      onError: handleProxyErrors,
      router: async (req) => { ... }
    })
)

What OS/version and node/version are you seeing the problem?

System:
    OS: Linux 5.13 Ubuntu 20.04.4 LTS (Focal Fossa)
    CPU: (16) x64 11th Gen Intel(R) Core(TM) i9-11950H @ 2.60GHz
    Memory: 16.28 GB / 31.06 GB
    Container: Yes
    Shell: 5.0.17 - /bin/bash


### Additional context (optional)

_No response_
chimurai commented 2 years ago

You can actually use Express' error handler to catch the error:

app.use((err, req, res, next) => {
  console.error(err)
  res.writeHead(500, {
    "Content-Type": "text/plain",
  });
  res.end("Internal server error.");
});