You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS API中got(options)错误无法返回至前端的问题

解决Node.js API错误信息无法返回前端的问题

你的核心问题是服务层捕获错误后没有向上抛出,导致控制器无法获取原始错误信息,最终返回默认500错误。以下是具体修复方案:

1. 修复服务层代码

在服务层的错误捕获逻辑中,打印完错误后必须重新抛出错误(或自定义错误对象),让错误能传递到控制器处理:

async function deletePayment(paymentId) {
  const options = await ApiOptionsService.deleteItem(paymentId);

  try {
    const response = await got(options);
    return response.body;
  } catch (err) {
    console.log('error ' + err.message);
    console.log('error ' + JSON.stringify(err.body));
    // 抛出错误,让控制器的catch捕获
    throw new Error(err.message);
    // 如果需要返回更详细内容,可抛出自定义对象:
    // throw { 
    //   message: err.message, 
    //   details: err.body,
    //   statusCode: err.response?.statusCode || 500 
    // };
  }
}

2. 修复控制器代码

控制器需要捕获服务层抛出的错误,主动将错误信息返回给前端,而非直接调用next(err)(这会触发Express默认错误处理,返回500):

router.delete('/deletePayment/:id', (req, res) => {
  squarePaymentService.deletePayment(req.params.id)
    .then(paymentResponse => res.send(paymentResponse))
    .catch(err => {
      // 根据错误类型设置合适状态码,比如400/404/500
      const statusCode = err.statusCode || 400;
      // 返回错误信息给前端
      res.status(statusCode).send({ error: err.message });
      // 如果是自定义错误对象,直接返回:
      // res.status(statusCode).send(err);
    });
});

原代码失效原因

你之前在got(options).catch()中仅打印错误但未抛出,导致deletePayment函数继续执行return response.body。此时response为undefined(catch无返回值),会触发新的Cannot read properties of undefined错误,最终控制器的next(err)返回默认500错误,原始错误信息根本没传递到前端。

内容的提问来源于stack exchange,提问作者coder123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 23:20:20