【问题标题】:Properly Throw an Error from an Axios Call从 Axios 调用中正确抛出错误
【发布时间】:2020-05-16 01:41:28
【问题描述】:

我有两个应用程序(appA、appB)。 A呼叫B

AppA 端点是

    api.get('/', (req, res, next) => {
        return axios({
            method: "GET",
            url: "http://localhost:3060/api/"
        }).then((data) => {
            return data.data
        }).catch((err) => {
            const {config, request, response} = err
            let e = new Error(`Rethrowing the "${"B"}" error FROM A`)
            e.stack?.split('\n').slice(0,2).join('\n') + '\n' + response.data;
            throw e
        })
    });

AppB 是:

    api.get('/', (req, res) => {
        throw new Error('B')
    });

我的目标是将 AppB 中的错误附加到 AppA 中的新错误中,并将其发送给调用 AppA 的人。当我尝试从 axios 调用中抛出错误时,控制台中打印出错误并显示nhandledPromiseRejectionWarning: Error: Rethrowing the "B" error FROM A。并且端点只是超时。

如何正确抛出 Axios Catch 中的附加错误?我想发送带有错误消息的堆栈跟踪。

谢谢

【问题讨论】:

    标签: node.js express error-handling axios


    【解决方案1】:

    您只需要从您的 AppB 发送错误响应

    api.get('/', (req, res) => {
           res.status(500).send('send your error')
    });
    

    现在,当您从 AppA 拨打电话时,如果您收到来自 AppB 的错误

          that error directly throw to catch block of your AppA 
    
        // AppA
        .catch((err) => {
           //you will receive your AppB error here if you set status code as 500 or any other error status code 
        })
    

    你的情况有两种可能:

    来自 AppA / AppB 的错误

    如果您收到来自 AppA 的错误,那么您可以抛出错误并从 catch 块向您的用户发送响应

    否则,如果您收到来自 AppB 的错误,那么您可以发送带有状态代码 500 的响应意味着错误从服务器到您的 AppA 因此,由于 500 状态代码,您的 AppA 将直接在 catch 块中将此错误作为错误并且您的 AppA 将直接向您的用户发送错误。

    【讨论】:

    • 如果您有任何疑问,请告诉我。
    • 嘿,谢谢你的回答,所以如果我想发送堆栈跟踪我不能使用错误对象?
    【解决方案2】:

    你可以这样发送错误:

     api.get('/', (req, res, next) => {
            return axios({
                method: "GET",
                url: "http://localhost:3060/api/"
            }).then((data) => {
                return data.data
            }).catch((err) => {
               let errorStack = new Error(err);
               res.status(500).send(errorStack.toString()) // This will send the error stack
            })
        });
    

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2019-01-03
      • 2017-10-18
      • 2018-03-18
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多