next.js 带有正确状态码的自定义错误页面

dm7nw8vv  于 2022-12-18  发布在  其他
关注(0)|答案(1)|浏览(163)

我关注了下一个docs regarding a custom error page。如果在getStaticProps发生某些错误,我想重用错误页面。类似于:

const Page: NextPage<Props> = ({ pageData, error }: Props) => {
  if (error) return <Error statusCode={500} />;
  return <Page data={pageData} />;
};

export const getStaticProps: GetStaticProps = async ({
  params,
}: {
  params: { [prop: string]: string[] };
}) => {
  const { slug } = params;
  const {pageData, error} = getPageData(slug)

  return {
    props: {
      pageData: page || null,
      error: error || null,
    },
  };
};

export default Page;

错误页面与文档中的页面相同:

function Error({ statusCode }) {
  return (
    <p>
      {statusCode ? `An error ${statusCode} occurred on server` : 'An error occurred on client'}
    </p>
  );
}

Error.getInitialProps = ({ res, err }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
  return { statusCode };
};

export default Error;

这是可行的,但状态码是错误的。Nextjs仍然用状态码200来响应对该页面的请求。我需要它将状态码设置为500,就像有服务器错误一样。

oxf4rvwz

oxf4rvwz1#

如果您使用“getServerSideProps”或“getStaticProps”,则可以更改页面状态代码,您只需要在返回页面属性之前更改响应状态代码:

const HomePage = ({pageProps}) => {

 if (pageProps.hasError) {
     return <CustomError status={error.status} message={error.message}/>
 }

 return <div>This is home page </div>

 }

 export const getServerSideProps = async ({req,res}) => {

 try {
     const homeData = await fetchHomeData()

     return {
         props: {
             data: homeData
         }
     }

 } catch (err) {

     res.statusCode = exception.response.status  /* this is the key part */

     return {
         props: {
             hasError: true, error: {
                 status: exception.response.status || 500,
                 message: exception.message
             }
         }
     }
 }
}

相关问题