【问题标题】:Handling errors within custom SWR hook处理自定义 SWR 挂钩中的错误
【发布时间】:2021-03-27 10:02:48
【问题描述】:

我编写了一个自定义钩子,它使用 SWR 从我的 API 中检索数据,同时为请求设置“身份验证”标头。

钩子对所有成功的请求都可以正常工作,但我希望能够处理失败的请求(400 个状态代码)。

我可以使用来自const res = await fetch(url 的结果访问状态代码,但是如何将error 参数中的错误返回给钩子的调用者?

import useSWR from 'swr';

export default function useAPI(path) {
  const auth = useAuth();

  const { data, error, isValidating, mutate } = useSWR(
    !path ? null : `${process.env.NEXT_PUBLIC_API_URL}${path}`,

    async (url) => {
      const res = await fetch(url, {
        headers: {
          Authorization: `Bearer ${auth.user.token}`,
          accept: 'application/json',
        },
      });

      return res.json();
    }
  );
  return { data, error, isValidating, mutate };
}

【问题讨论】:

    标签: reactjs next.js swr


    【解决方案1】:

    来自SWR Error Handling 文档:

    如果在 fetcher 内部抛出错误,钩子会返回 error

    在您的情况下,您可以简单地在 fetcher 中处理 400 状态代码响应,并在处理完成后抛出错误。

    const { data, error, isValidating, mutate } = useSWR(
        !path ? null : `${process.env.NEXT_PUBLIC_API_URL}${path}`,
        async (url) => {
            const res = await fetch(url, {
                headers: {
                    Authorization: `Bearer ${auth.user.token}`,
                    accept: 'application/json'
                }
            });
    
            if (res.statusCode === 400) {
                // Add your custom handling here
    
                throw new Error('A 400 error occurred while fetching the data.'); // Throw the error
            }
    
            return res.json();
        }
    );
    

    【讨论】:

    • 完美,谢谢 - 效果很好。仅供其他人参考,我像这样捕获错误: const { data, error } = useAPI(/equipment/${id}); useEffect(() => { // 处理错误 }, [error]);
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 2019-10-19
    • 2021-09-08
    • 2018-10-12
    • 2019-10-09
    • 2022-01-27
    相关资源
    最近更新 更多