【问题标题】:Error handling in async routing in Express.jsExpress.js 中异步路由中的错误处理
【发布时间】:2018-10-05 10:02:38
【问题描述】:

我在下面有快速路由,它可以工作。但是,如果 axios 由于错误而无法检索任何信息,我无法使用 res.send 进行响应,但我可以在终端中看到错误日志。我怎样才能捕捉到错误?理想情况下,如果它无法检索数据,它应该响应“无法连接”。

router.get('/accounts', async (req, res) => {
  try {
    const response = await axios.get(`${config.url}/accounts`, {
      auth: config.auth
    });
    const data = await response.data.results;
    res.json(data);
  } catch (e) {
    console.log(e);
    res.send('Could not connect');
  }
});

【问题讨论】:

  • 您的 sn-p 有效。当axios 出现错误时,我的客户会收到Could not connect

标签: node.js express async-await axios


【解决方案1】:

问题在于您尝试解析循环 JSON 对象的 catch 块。我建议使用json-stringify-safe 库来解决您的问题:

安装 json-stringify-safe:

    $ npm install json-stringify-safe --save

解决方案:

const express = require('express')
const axios = require('axios');
const app = express();
var stringify = require('json-stringify-safe');


app.get('/accounts', async (req, res) => {
    try {
        const response = await axios.get('someInvalidUrl'); // will throw error
        return res.json(response);
    } catch (e) {
        e = JSON.parse(stringify(e)); // safely parse circular JSON object
        res.send(e); // will return error as json
    }
});

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 2020-05-11
    • 2017-08-08
    • 2017-11-16
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多