abstract api call and try catch block 到 JavaScript 中的一个常用方法,使其更可重用

abstract api call and try catch block into one common method in JavaScript to make it more reusable

export const getDatilsCall = async (testId) => {
  try {
    const resp = await axiosInstance.get(
      getUrl(DETAILS, { urlParams: { testId } })
    );
    return resp.data;
  } catch (err) {
    throw handleExceptions(err);
  }
};

export const getDefaultCall = async (productId) => {
  try {
    const resp = await axiosInstance.get(
      getUrl(DEFAULT, { queryParams: { productId } })
    );
    return resp.data;
  } catch (err) {
    throw handleExceptions(err);
  }
};

假设有一个api.js文件包含上述方法,“getUrl”和“handleExceptions”已经抽象出来,我可以直接使用它们。但似乎对于每个 api 调用,我们都需要复制 try catch 块,包括“await axiosInstance.get”“return resp.data”等...

你们认为我们是否需要为上述方法抽象try catch 块,或者当前的方式是否足够好。谢谢

根据评论更新我的问题。我删除 try/catch 并在顶层使用 try/catch 怎么样,但是我如何处理错误部分呢?我需要在顶层抛出 handleExceptions(err) 吗?

    export const getDefaultCall = async (productId) => {
      
        const resp = await axiosInstance.get(
          getUrl(DEFAULT, { queryParams: { productId } })
        );
        return resp.data;
     
    };

我查看了您的 post 更新,我认为有两种选择

  1. 如果你想管理特定的错误,关于在你的函数中调用 axios 或其他代码,你可以在你的函数中使用“try catch”getDefaultCall,例如:
 export const getDefaultCall = async (productId) => {
  try {

    const resp = await axiosInstance.get(
      getUrl(DEFAULT, { queryParams: { productId } })
    );

    // await anythings

    // await anythings

    return resp.data;
  } catch (err) {
    // manage special error, like custom message, or response structure json for other error manager
  }
};

但是,

  1. 如果您只想管理错误,您可以删除 getDefaultCall 中的“try catch”并在顶层控制您的错误
export const getDefaultCall = async (productId) => {
  const resp = await axiosInstance.get(
    getUrl(DEFAULT, { queryParams: { productId } })
  );
  return resp.data;
};

// use

something() {
  try {
    // if getDefault Call fail, jump auto to catch
    const data = await getDefaultCall();

  } catch (err) {
    
  }
}