无法从 useSWR 错误属性获取响应错误

jul*_*nna 2 reactjs fetch-api next.js swr

我正在使用 Next.js,并在将其集成到我的应用程序之前尝试对 SWR 进行一些测试。因此,下面只是一个 faker.api 测试,看看它的运行情况并熟悉它。

一切都工作得很好,但由于某种原因,我似乎无法恢复错误,我的控制台日志没有在控制台中打印任何内容。

import type { NextPage } from 'next'
import { useState } from 'react'
import useSWR, { SWRConfig } from 'swr'
import UseBooks from '../Hooks/UseBooks'

type HomeProps = NextPage & {
  serverData: any
}

const fetcher = (url:string) => fetch(url).then(r => r.json()) 

const Home = ({serverData}: HomeProps) => {
const [shouldFetch, setShouldFetch] = useState(false)
const {data, error} = useSWR(
  `https://fakerapi.it/api/v1/ompanies?_quantity=10`,
  fetcher,
  {
    fallbackData: serverData,
    onError: (error, key)=> {
     console.log(error)
    }
  })

const  [booksData, booksError]  = UseBooks(shouldFetch, 'https://fakerapi.it/api/v1/books?_quantity=10')
const handleClick = () => {
  setShouldFetch(true)
}

  return (
    <div>
        {JSON.stringify(booksData)}
        <ul>
          {data?.data?.map(el => (
            <li key={el.id}>{el.name}</li>
          ))}
        </ul>
        <button onClick={handleClick}>next</button>
    </div>
  )
}

export async function getServerSideProps(){
  const res = await fetch(`https://fakerapi.it/api/v1/companies?_quantity=10`)
  const serverData= await res.json()
  return{ props:{serverData}}
}

export default Home
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 5

这是预期的行为,因为fetch当请求返回非 2xx 响应时实际上不会拒绝,它仅在发生网络错误时才会拒绝。如果您登录data到控制台,您会注意到它包含错误响应正文:{ status: "Not found", code: 404, total: 0 }

您可以使用fetch响应的ok属性来确定请求是否返回 2xx 响应,如果没有返回则自行抛出错误。

const fetcher = (url: string) => fetch(url).then(r => {
    if (!r.ok) {
        throw new Error('Something went wrong with the request')
    }
    return r.json()
}) 
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用axios- 因为当返回非 2xx 响应时它会抛出错误。

const fetcher = (url: string) => axios(url).then((r) => r.data);
Run Code Online (Sandbox Code Playgroud)