【问题标题】:Express and MongoDB, how to manualy throw the error in the route controllers?Express 和 MongoDB,如何在路由控制器中手动抛出错误?
【发布时间】:2022-09-28 17:38:01
【问题描述】:

我是 Express 的新手,我正在尝试在顶层应用一些错误处理。

在我的控制器文件中,我有一个控制器来获取所有游览。

exports.getAllTours = async (req: Request, res: Response) => {
  //Execute query
  const features = new APIFeatures(Tour.find(), req.query)
    .filter()
    .sort()
    .limitFields()
    .paginate();

  // Endpoint: http://localhost:8000/api/v1/tours
  // Enter a wrong URL here will not even trigger the console.log function.
  // But I want to throw the error right here, not in the app.all(\'*\')
  console.log(\"features\", features);

  if (!features) {
    throw new NotFoundError(\"Tours Not Found\");
  }

  //same problem here.
  const tours = await features.query;
  console.log(\"tours\", tours.length);

  if (!tours) {
    throw new NotFoundError(\"Tours Not Found\");
  }

  res.status(200).json({
    status: \"success\",
    result: tours.length,
    data: {
      tours,
    },
  });
};

我有一个像这样扩展 Error 类的 CustomError 类。

const httpStatusCode = require(\"./httpStatusCode\");

class CustomError extends Error {
  constructor(message: string, statusCode: number, description: string) {
    super(description);

    //Object.setPrototypeOf(this, new.target.prototype);
    this.message = message;
    this.statusCode = statusCode;
  }
}
module.exports = CustomError;


class NotFoundError extends CustomError {
  constructor(message, statusCode) {
    super(message, statusCode);
    this.message = message;
    this.statusCode = httpStatusCode.NOT_FOUND;
  }
}

module.exports = NotFoundError;

还有一个错误处理中间件:

import { NextFunction, Request, Response, ErrorRequestHandler } from \"express\";

module.exports = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  err.statusCode = err.statusCode || 500;
  err.status = err.status || \"error\";
  res.status(err.statusCode).json({
    status: err.status,
    message: err.message,
  });
};

最后,我使用应用程序中的 errorHandler 中间件来捕获所有错误。 但是,问题是 getAllTours 控制器中的所有错误都不会被抛出,而是会在 app.all() 中抛出:

app.use(\"/api/v1/tours\", tourRouter);
app.all(\"*\", (req: Request, res: Response) => {
  throw new NotFoundError(\"Page Not Found\");
  //next(new AppError(`Can\'t find ${req.originalUrl} on this server`, 404));
});

app.use(errorHandler);

我知道由于端点已更改并在 app.all() 中抛出是有意义的。但是如何在 getAllTours 控制器中手动抛出错误? 我使用 express-async-error 所以我可以在异步函数中使用 throw 关键字。

  • \"在此处输入错误的 URL 甚至不会触发 console.log 功能\".你是什​​么意思?什么是“错误的 URL”?如果您使用的 URL 与路由不匹配,则不会调用处理程序根本. tourRouter 是什么,getAllTours 被调用的是哪条路由?您的问题很可能不在于您的错误处理,而在于您的路线处理。

标签: mongodb express asynchronous mongoose error-handling


【解决方案1】:

我想通了。

Handle Express async error

我不知道 Express 版本 4 无法通过简单地抛出一个新错误来处理异步错误。我仍然不确定 Express 版本 5 现在是否可以处理它。 但我最终使用ExpressJS Async Errors 解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2016-03-27
    • 2017-04-14
    • 2014-04-11
    相关资源
    最近更新 更多