如何解决将 api 调用和 try catch 块抽象为 JavaScript 中的一种常用方法,使其更具可重用性
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;
};
解决方法
我查看了您更新的帖子,我认为有两种选择
- 如果你想管理特定的错误,关于在你的函数中调用 axios 或其他代码,你可以在你的函数
getDefaultCall
中使用“try catch”,例如:
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
}
};
但是,
- 如果您只想管理错误,您可以删除
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) {
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。