处理自定义 SWR 挂钩中的错误

Moo*_*ter 7 reactjs fetch-api next.js swr

我编写了一个自定义挂钩,它使用 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 };
}
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 6

来自SWR 错误处理文档:

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();
    }
);
Run Code Online (Sandbox Code Playgroud)