Node.js 如何使用适配器更改Axios中的结果状态? 为什么

Node.js 如何使用适配器更改Axios中的结果状态? 为什么,node.js,axios,adapter,axios-retry,Node.js,Axios,Adapter,Axios Retry,我们正在使用库,它在内部使用以下代码: axios.interceptors.response.use(null,error=>{ 由于它仅指定错误回调,因此会显示: 任何超出2xx范围的状态代码都会触发此功能 不幸的是,我们正在调用一个非RESTful API,它可以返回200,并且在主体中有一个错误代码,我们需要重试 在本例中,我们尝试在Axios重试之前添加Axios拦截器并更改结果状态;但这并没有触发后续的拦截器错误回调 我们的工作是指定一个自定义适配器。然而,这并没有很好的文档记录,我

我们正在使用库,它在内部使用以下代码:

axios.interceptors.response.use(null,error=>{

由于它仅指定错误回调,因此会显示:

任何超出2xx范围的状态代码都会触发此功能

不幸的是,我们正在调用一个非RESTful API,它可以返回200,并且在主体中有一个错误代码,我们需要重试

在本例中,我们尝试在Axios重试之前添加Axios拦截器并更改结果状态;但这并没有触发后续的拦截器错误回调

我们的工作是指定一个自定义适配器。然而,这并没有很好的文档记录,我们的代码并不能处理所有情况

代码 这适用于错误情况,即打印:

retry checking response 500 retry checking response 500 retry checking response 500 retry checking response 500 Service returned Request failed with status code 500 重试检查响应500 重试检查响应500 重试检查响应500 重试检查响应500 服务返回的请求失败,状态代码为500 它也适用于成功案例(将URL更改为):

结果:{code:201,description:'Created'} 问题 但是,将URL更改为会导致:

(node:19759) UnhandledPromiseRejectionWarning: Error: Request failed with status code 404 at createError (.../node_modules/axios/lib/core/createError.js:16:15) at settle (.../node_modules/axios/lib/core/settle.js:18:12) (节点:19759)未处理的PromisejectionWarning:错误:请求失败,状态代码404 在createError(…/node_modules/axios/lib/core/createError.js:16:15) 在结算时(…/node_modules/axios/lib/core/solite.js:18:12)
httpAdapter
调用上的
catch
将捕获该错误,但是我们如何将其传递到链中呢

实现Axios适配器的正确方法是什么

如果有更好的方法来处理这个问题(除了分叉axios重试库),这将是一个可以接受的答案

更新 一位同事发现,在
httpAdapter
调用上执行
.catch(e=>reject(e))
(或者仅仅执行
.catch(reject)
)似乎可以解决这个问题。不过,我们仍然希望有一个实现Axios适配器的典型示例,该适配器封装了默认http适配器。

以下是有效的方法(在节点中):


当api返回与2xx不同的代码(使用axios)时,是否需要重试调用?@JRichardsz我们需要在几种情况下重试。问题是我们传递给axios retry的
retryCondition
回调通常不会在200个响应上被调用。在这一点上,我主要寻找一个实现axios适配器的示例,该适配器包装并委托给默认适配器。谢谢!这对我很有用,我会如果没有几天的努力,我自己是无法想出这个办法的。 Result: { code: 201, description: 'Created' } (node:19759) UnhandledPromiseRejectionWarning: Error: Request failed with status code 404 at createError (.../node_modules/axios/lib/core/createError.js:16:15) at settle (.../node_modules/axios/lib/core/settle.js:18:12)
const httpAdapter = require('axios/lib/adapters/http');
const settle = require('axios/lib/core/settle');

const customAdapter = config =>
  new Promise((resolve, reject) => {
    httpAdapter(config).then(response => {
      if (response.status === 200)
        // && response.data contains particular error
      {
        // log if desired
        response.status = 503;
      }
      settle(resolve, reject, response);
    }).catch(reject);
  });

// Then do axios.create() and pass { adapter: customAdapter }
// Now set up axios-retry and its retryCondition will be checked