打字稿:猫鼬转换为 ObjectId 在路径“_id”处的值失败

时间:2021-01-16 17:30:45

标签: javascript node.js typescript express

如果我故意尝试使用邮递员获取错误的产品 ID,应用程序就会崩溃。

原因

该错误没有被我的错误处理程序中间件捕获。

<块引用>

路线

/* returns a single product */
router.get("/:id", async (req: Request, res: Response) => {
  const product = await Product.findById(req.params.id);
  if (!product) {
    throw new NotFoundError();
  }
  res.send(product);
});
<块引用>

未找到错误(自定义)

import { CustomError } from "./custom-error";

export class NotFoundError extends CustomError {
  statusCode = 404;
  constructor() {
    super("Page not found");
    console.log("Not found error");    // <=== Not being consoled out
    Object.setPrototypeOf(this, NotFoundError.prototype);
  }
  serialize() {
    return [{ message: "Page not found" }];
  }
}
<块引用>

错误处理程序

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  if (err instanceof CustomError) {
    console.log("Error while processing request");   // <=== Not being consoled out  
    return res.status(err.statusCode).send({ errors: err.serialize() });
  }
  // and if not
  console.log(err);
  res.status(400).send({
    errors: [{ message: "Something went wrong" }],
  });
};

我不知道为什么 app.ts 文件中的中间件没有捕获错误:

// routes
app.use("/api/product", productFetchRouter);
// error handler
app.use(errorHandler);

Repo

2 个答案:

答案 0 :(得分:0)

尝试在路由之前声明中间件:

// error handler
app.use(errorHandler);

// routes
app.use("/api/product", productFetchRouter);
app.use(userFetchRouter);

答案 1 :(得分:0)

router.get("/:id", async (req: Request, res: Response, next: Next) => {
try{
const product = await Product.findById(req.params.id);
  if (!product) {
    throw new NotFoundError();
  }
  res.send(product);

}catch(e){
   next(e);
 }
});

router.use(errorHandler);

注意:我不太擅长打字稿,但我通常如何捕获错误,然后使用 next()

将其传递给 errorHandler 中间件