简体   繁体   English

使 axios catch() 函数在其他组件中可重用

[英]Making axios catch() function reusable in other components

I recently read this question and wanted to ask a more specific question in my scenario.我最近读了这个问题,想在我的场景中问一个更具体的问题。

I have many different axios components in my app, which all behave a bit differently in the then() function.我的应用程序中有许多不同的 axios 组件,它们在 then() 函数中的行为都有些不同。 However, I have a universally same catch() function, and I found myself repeating this huge code block in every axios function I have.但是,我有一个普遍相同的 catch() 函数,我发现自己在我拥有的每个 axios 函数中都重复了这个巨大的代码块。 This, of course, didn't seem to follow the DRY principle very well.当然,这似乎并没有很好地遵循 DRY 原则。

Is there a way to create a more flexible Axios component I can reuse, or just a way to avoid pasting the catch() block everywhere?有没有办法创建一个我可以重用的更灵活的 Axios 组件,或者只是一种避免将 catch() 块粘贴到任何地方的方法?

axios
  .patch/delete/get/post(
    "API ROUTE URL",
    {
      withCredentials: true,
    }
  )
  .then(function (response) {
    // stuff like...
    // setDrafts(response.data.results);
    // setState(response.data);
    // alert(message);
  })
  .catch(function (error) {
    // this portion is the same universally
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      console.log(error.request);
    } else {
      console.log('Error', error.message);
    }
    toast.error(
      `ERROR ${error.response.status}: 
      See console log for more info and please report this incident`,
      {
        duration: 4000,
        position: 'bottom-center',
      }
    );
    console.log(error.config);
  });

Simply create a catch function and reuse it wherever you want.只需创建一个catch function并在任何你想要的地方重用它。

const catch_func = (error) {
    // this portion is the same universally
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      console.log(error.request);
    } else {
      console.log('Error', error.message);
    }
    toast.error(
      `ERROR ${error.response.status}: 
      See console log for more info and please report this incident`,
      {
        duration: 4000,
        position: 'bottom-center',
      }
    );
    console.log(error.config);
  }

axios
  .patch/delete/get/post(
    "API ROUTE URL",
    {
      withCredentials: true,
    }
  )
  .then(function (response) {
    // stuff like...
    // setDrafts(response.data.results);
    // setState(response.data);
    // alert(message);
  })
  .catch(catch_func);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM