简体   繁体   English

ExpressJS - 错误处理程序不处理任何错误

[英]ExpressJS - Error Handler Not Handling Any Errors

I have a problem with my error handler like below:我的错误处理程序有问题,如下所示:

export const errorHandler = (
    error: Error,
    req: Request,
    res: Response,
    next: (error: Error) => void,
  ) => {
    console.log("TEST");
    next(error);
}

It is very simple but I have a problem with launching it on errors, here is my index.js:这很简单,但我在错误时启动它时遇到问题,这是我的 index.js:

export const server = http.createServer(app);

const initServer = () => {
  app.use(bodyParser.json({ limit }));
  app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));

  app.use(express.json());
  app.use(cors({ credentials: true, origin: true }));

  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(router);

  app.use(errorHandler); //IS HERE

  server.listen(PORT, () => {
    logger.info(`Server running on port ${PORT}`);
  });
};

initServer();

Can someone tell me why it is not working when I call an request when I set:有人可以告诉我为什么当我设置时调用请求时它不起作用:

throw new Error("ERROR");

Thanks for any answer, thanks!感谢您的任何回答,谢谢!

PS.附言。 router file is here: router文件在这里:

export const router = express.Router({ mergeParams: true });

router.get("/account/login", login);

//and more...

you have to enclose your response within the errorHandler middleware... let me show you how I do this你必须将你的响应包含在 errorHandler 中间件中......让我告诉你我是怎么做到的

I create a generic middleware which is used in every route我创建了一个在每条路线中使用的通用中间件

this is in Typescript, if you use only Javascript just remove the types (it's easy to port)这是在 Typescript 中,如果你只使用 Javascript 只需删除类型(很容易移植)

return async function (req: Request, resp: Response, next) {
        try {
            const response = await fn(req, resp, next);
            resp.status(200).send(response);
        } catch (e) {
           // here you can handle the error the way you wish to

           // I throw all my errors as ErrorObject ( a custom class)
           // so I can send user formatted errors, you can implement this
           // however you wish to
           
            if (e instanceof ErrorObject) {
                const error = e.json();
                resp.status(e.statusCode).send(error);
            } else next(e);
        }
    };

Now any of your route should use this middleware as follows现在你的任何路线都应该使用这个中间件如下


router.post(
  "/your-route",
  expressResponse((req, resp) => {
     // do want you want
  }),
);

If you are using express 4.x or earlier, and you are using asynchronous route handlers, you need to catch any encountered errors and pass them explicitly to next() in order for them to be processed by your error handler.如果您使用的是 express 4.x 或更早版本,并且您正在使用异步路由处理程序,则需要捕获任何遇到的错误并将它们显式传递给next()以便错误处理程序处理它们。

I have a helper function I use to wrap async handlers in my projects that looks like this:我有一个助手 function,我用它来在我的项目中包装异步处理程序,如下所示:

/**
 * Wrapper for async route handlers that passes Promise-based errors to next().
 *
 * NOTE: Starting with Express 5 (which is not released as of this note) exceptions
 *  in async middleware will be handled as expected, and this asyncMiddleware will
 *  no longer be needed.
 *
 * When an async route handler rejects a Promise, it is important that the
 * Express error handler be invoked to end the request cleanly. This wrapper
 * function supports the idiomatic:
 *
 *  router.use('/path', asyncMiddleware(async(req, res) => {
 *     await db.save();     // permitted b/c we are async
 *     if (something_bad) {
 *          throw(...);     // reject promise, and invokes Express error handler
 *     }
 *     return res.send({}); // resolve promise normally
 *  }
 */
export const asyncMiddleware =
    fn => (req: Request, res: Response, next: NextFunction) => {
        Promise.resolve(fn(req, res, next)).catch(next);
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM