1

我有一个现有的 Node Express 应用程序并希望更好地改进错误处理。我当前的路由端点定义如下所示,

app.get('/example/getActiveId', async (req, res, next) => {
  // Some code to fetch some details from request and do some validations

  try {
    const result = await api.getActiveId(id); 
    res.json({ success: true, result });       // I am getting this response in all the time.
  } catch (err) {
    console.log('getActiveId', err)
    console.error(err);
    res.json({ success: false });
  }
});

另外,我在所有路由路径的最后定义了错误中间件。

// error handler middleware
app.use((error, req, res, next) => {
  console.log('in Error middleware')
  console.error(error.stack);
  res.status(500).send(error.message || 'Something Broke!');
 })

我的定义getActiveId如下。

 exports.getActiveId = id => axiosInstance
  .get('/example')
  .then(({ data }) => data)
  .catch(er => er);

上面getActiveId定义中的问题是每次catch的时候getActiveId,执行落入上面端点定义的try块。我希望执行应该进入 catch 块端点定义函数。这样我就可以调用next(err)默认的快速错误处理中间件。

所以我尝试了下面的模型代码来模仿承诺拒绝。

exports.getActiveId = id => {
    const __mockPromise = () => {
        return new Promise((resolve, reject) => {
            reject('Problem in getActiveId')
        })
    }

    return new Promise((resolve, reject) => {
        __mockPromise().then(({ data }) => resolve(data)).catch(er => { console.log('in catch....'); reject(er) })
    });
}

我预计上述函数将进入终点函数定义的 catch 块。

但是这次我收到以下错误,

in catch....
(node:32897) UnhandledPromiseRejectionWarning: Problem in getActiveId
(node:32897) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)

如何修复此错误并绕过执行错误中间件?

4

1 回答 1

0

使用您当前的代码,api.getActiveId始终返回已解决的承诺

  • 如果axiosInstance.get成功,则解析为data
  • 如果axiosInstance.get失败,则将.catch(er => er)其解析为er.

如果你想api.getActiveId返回一个被拒绝的承诺er,请省略.catch(er => er).

例如,如果您使用以下输入运行 Node.js

const getActiveId = () => Promise.reject("error")
  .then(({ data }) => data);
async function test() {
  try {
    const result = await getActiveId();
    console.log(result);
  } catch (err) {
    console.error(err);
  }
}
test();

将达到该console.error声明,并且不会报告未处理的承诺拒绝。

于 2021-10-26T13:37:08.213 回答