Question丨async/await 必定要加 try/catch 嗎?

ES7的 async/await 組合相信如今你們已經用得爐火純青了,是一個異步請求目前較優的處理的方案。爲了保證程序的穩定運行,咱們還會加上 try/catch 處理可能拋出的錯誤。

文章篇幅不長,可慢慢品 ~前端

若是 async/await 不加 try/catch 會發生什麼事?

// 模擬異步請求
const sleep = (isSuccess) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (isSuccess) {
        resolve("success");
      } else {
        reject("failure");
      }
    }, 1000);
  });
};

const getRes1 = async () => {
  const res1 = await sleep(false);
  // Promise 返回 reject ,底下的代碼塊不被執行
  console.log("do something...");
};

getRes1();

調用 getRes1() 會發生什麼ios

  1. 致使瀏覽器報錯:

一個未捕獲的錯誤axios

瀏覽器的報錯,咱們是確定要處理的,由於這可能會影響到程序的正常運行。後端

  1. const res1 = await sleep(false); 底下的代碼不被執行

咱們能夠通俗的理解,await xxx() 底下的代碼塊都是 Promise 返回的 resolve,若是 Promise 返回的是 reject,那麼代碼塊將不會被執行。瀏覽器

可是若是是這種場景是能夠執行的,由於它們已經不在一個相同的「代碼路徑」,如:框架

const created = () => {
  getRes1();
  console.log("do something...");
};
created();
// do something...

雖然不影響程序的運行,可是程序依然會報錯。若是咱們有在前端工程裏有加入錯誤監控,如 Fundebug ,或者其餘。那麼將會有不少 error 級的日誌,可能會混淆咱們去排查/更準確的跟蹤錯誤。異步

延伸到實際業務場景

咱們在實際的業務中,通常會用第三方請求框架如 Axios ,咱們還會與友好的後端小夥伴約定接口返回體,如:async

interface IResult<T> {
  code: 200 | 500;
  data: T | null;
  message: string;
}

接下來咱們來模擬一下常見的業務場景,如:獲取用戶信息post

Axios.js【模擬】this

const Axios = (function () {
  function Axios(isTimeout = false, isExist = true) {
    this.isTimeout = isTimeout;
    this.isExist = isExist;
  }
  Axios.prototype.get = function (path, params = {}) {
    const resObj = ({ code, data = null, message }) => ({
      code,
      data,
      message
    });
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 當接口請求沒有錯誤
        if (!this.isTimeout) {
          // 當用戶存在
          if (this.isExist) {
            resolve(
              resObj({
                code: 200,
                data: { id: 1, name: "張三" },
                message: "獲取用戶成功"
              })
            );
          } else {
            // 當用戶不存在
            resolve(
              resObj({
                code: 500,
                message: "用戶不存在"
              })
            );
          }
        }
        // 當接口請求出現錯誤,如請求超時
        else {
          reject("timeout of 10000ms exceeded");
        }
      }, 1000);
    });
  };
  Axios.prototype.post = function (path, params) {};
  return Axios;
})();
export default Axios;

調用

const axios = new Axios(true);
const created = async () => {
  try {
    const { code, data, message } = await axios.get("/getUserInfo");
    if (code === 200) {
      // do something...
      console.log(data);
    } else if (code === 500) {
      // do something...
      alert(message);
    }
  } catch (err) {
    console.log("err :>> ", err);
  }
};
created();
// err :>>  timeout of 10000ms exceeded

這裏,咱們老老實實的用了 try/catch 進行包裹,防止控制檯報超時錯誤。
回顧剛剛咱們有說到的,
若是在 await 底下的代碼,不在一個相同的「代碼路徑」,那麼是不會影響到程序繼續運行的,只是會報了個錯,可是會影響到咱們定位程序中的一些錯誤問題,這就會讓咱們有一種 「不加 try/catch 不行,加了又以爲多餘的感受」 ,若是在一些複雜的業務場景下,冥冥之中就會提高咱們的心智負擔。

讓咱們再看下標題:async/await 必定要加 try/catch 嗎?答:能夠不要加。

keep going >>>

async/await 如何優雅的不加 try/catch

二次封裝 "Axios",

對於 Axios ,小夥伴們應該都是 「老封裝了」 ,那這裏咱們再來探討下

MyAxios.js

import Axios from "./Axios";
const axios = new Axios(true);
const MyAxios = (function () {
  function MyAxios() {}
  MyAxios.prototype.get = function (path, params = {}) {
    return axios.get(path).catch((err) => {
      // return Promise.resolve({
      //   code: 444,
      //   data: null,
      //   message: "catch error",
      //   err
      // });
      // 可不用 Promise.resolve 靜態方法,由於在Promise鏈裏返回的都會是一個 Promise 對象
      return {
        code: 444,
        data: null,
        message: "catch error",
        err
      };
    });
  };
  MyAxios.prototype.post = function (path, params) {
    return axios.post(path).catch((err) => {
      return {
        code: 444,
        data: null,
        message: "catch error",
        err
      };
    });
  };
  return MyAxios;
})();
export default MyAxios;

調用

const myAxios = new MyAxios();
const created = async () => {
  const { code, data, message, err } = await myAxios.get("/getUserInfo");
  if (code === 200) {
    // do something...
    console.log(data);
  } else if (code === 500) {
    // do something...
    alert(message);
  } 
  // 不用到則不寫
  else if (code === 444) {
    console.log(message);
    console.log("err :>> ", err);
  }
};
created();

總結

咱們經過二次封裝,把 Axios 返回的 reject ,捕獲(catch)以後 return 一個咱們前端本身約定的 code 是444的,多了一個 err 字段的對象。這樣子咱們就不須要在每一個有 async/await 的地方都用 try/catch 進行包裹來防止系統報錯,若是這個接口須要你在 「catch 時」 處理一些業務邏輯,那就判斷 code === 444,不須要的話,就不用寫。但一般,咱們會在 MyAxios.js 用一種全局彈框的方式,來友好的告知用戶:「接口有點問題,請稍後再試」。

相關文章
相關標籤/搜索