NodeJS Axios捕获崩溃代码,标记为“UnhandledPromiseRejection”

fdx2calv  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(160)

我正在处理一个axios呼叫失败。我写了函数和代码:

async function createFunction (url, APIKEY, vendorType) {
  return new Promise((resolve, reject) => {
    const options = {
      method: 'post',
      maxBodyLength: Infinity,
      url: `${url}/vendors/packages`,
      headers: { 
        'x-api-key': `${APIKEY}`
      },
      timeout: 10000,
      data: {
        "contentType": vendorType,
      }
    };
    axios.request(options)
    .then(response =>{
      if (response.status && response.status == 200) {
        resolve(response);
      } else {
        reject(`createFunction Axios call failed with status ${response.status}: ${response.data}`)
      }
    }).catch(err => {
      reject(`createFunction Axios call failed: ${err}`);
    })
  });
}

KbartFunctions.createPackage(host,APIKEY,vendortype)
.then((response) => {
console.log(response);
})

字符串
我收到一个错误:

[UnhandledPromiseRejection: 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(). The promise rejected with the reason "createFunction Axios call failed: AxiosError: Request failed with status code 400".] {
  code: 'ERR_UNHANDLED_REJECTION'
}


我以为我正确地处理了拒绝,但代码还是崩溃了。因为错误内容是“createFunction Axios call failed:“,所以我知道它在Catch段中,而不是在then段中(否则它会说“createFunction Axios call failed with status”)。
我做错了什么?

6rvt4ljy

6rvt4ljy1#

代码中的几个问题:

  • 调用代码中缺少catch方法调用:KbartFunctions.createPackage(...)
  • 不必要地使用Promise构造函数,它是一个anti-pattern

axios.request已经返回了一个promise,所以不需要使用Promise构造函数自己创建一个新的promise。你可以只返回axios.request(...)返回的promise。
你的代码可以简化如下:

function createFunction(url, APIKEY, vendorType) {
  const options = {
    ...
  };

  return axios
    .request(options)
    .then(response => {
      if (response.status && response.status == 200) {
        return response;
      } else {
        throw new Error(
          `createFunction Axios call failed with status ${response.status}:${response.data}`
        );
      }
    });
}

KbartFunctions.createPackage(host, APIKEY, vendortype)
 .then(response => {
   console.log(response);
 })
 .catch(error => { /* handle the error */ });

字符串
在重构代码中需要注意的几点:

  • createFunction函数中的catch方法调用已被删除。这是因为如果您只是抛出在catch方法回调中捕获的错误,则可以省略catch方法调用,并允许调用代码捕获和处理错误。
  • 您将createFunction标记为async函数,但没有使用async-await语法。相反,您使用了Promise Chaining。因此,我从函数签名中删除了async关键字。

如果你想使用async-await语法重写createFunction,可以如下所示:

async function createFunction(url, APIKEY, vendorType) {
  const options = {
    ...
  };

  const response = await axios.request(options);

  if (response.status && response.status == 200) {
    return response;
  } else {
    throw new Error(
      `createFunction Axios call failed with status ${response.status}: ${response.data}`
    );
  }
}

相关问题