首页 > 解决方案 > 在 express 中处理 javascript 错误

问题描述

假设我有以下异步功能

export async function someAsyncFunction() {
  const result = await fetchData();
  return result[0].id;
}

在我有的路线上

router.post(
  '/some-path',
  handleErrorAsync(async (req: Request, resp: Response, _err: Errback) => {
    const data = await someAsyncFunction();
    resp.json(data)
  })
);

而且我有错误处理功能

interface ResponseError extends Error {
  statusCode: number;
}

// Middleware to respond with an error when error caught
export function handleError(
  err: ResponseError,
  _req: Request,
  resp: Response,
  _next: NextFunction
) {
  if (err) {
    resp.status(err.statusCode || 500).json(err);
  }
}

export const handleErrorAsync = (func: Function) => (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  func(req, res, next).catch((error: Error) => {
    next(error);
  });
};

因此,如果例如fetchData有一个错误响应对象,这可以正常工作,但是当错误是常规 javascript 错误时,它无法打印错误对象,而是仅打印{}500 错误。

例如在这一行中return result[0].id;,如果结果为空([]),那么这将抛出TypeError,这将被handleError中间件捕获,但该.json(err)部分将只显示{}

有没有办法我可以使用相同的中间件同时获取服务器错误(正常工作)和内部服务器错误?

标签: javascriptnode.jsexpresserror-handling

解决方案


你可以扩展toJSONError的方法。

let a = new Error("hi")

console.log(JSON.stringify(a))

Error.prototype.toJSON = function () {
    const alt = {};
    // get all property
    Object.getOwnPropertyNames(this).forEach((key) => {
        alt[key] = this[key];
    });

    // only get message property
    // alt["message"] = this["message"]
    return alt;
}

console.log(JSON.stringify(a))

然后只需调用res.json(error),您将获得 Error 的属性。
因为当你调用时res.json(parameter),express会触发toJSON参数的方法。您可以在Is it possible to stringify an Error using JSON.stringify 中阅读更多内容? .
但是,我建议只在方法中公开“消息”属性toJSON


推荐阅读