如何在我的 React.js 和 Next.js 应用程序上模拟 HTTP 500 错误?

问题描述 投票:0回答:1

我想模拟此错误,以便根据最近的安全漏洞检查是否显示自定义错误页面,而不是 HTTP 500 页面。

我们在网站本身中对 404 和 403 进行了特殊处理,因此我想确保无需特殊处理的错误也能正常工作。

reactjs next.js http-status-code-500
1个回答
0
投票

通常,当 server 抛出未显式处理的错误时,会返回 500 响应。 (请参阅:处理服务器错误)。我在下面添加了两个

app
pages
场景。在这两种情况下,访问
/error
应产生 500 响应。


如果您使用

app
API,添加一个在服务器上引发错误的页面应该可以解决问题。

// app/error/page.jsx

export default function Page() {
  throw new Error("don't catch me for a 500 response");
  return <h1>you should not see me</h1>;
}

确保该组件标记为客户端组件(文件顶部没有

"use client"
)。当标记为客户端组件时,错误将由客户端而不是服务器抛出。因此不会产生 500 响应。


如果您使用

pages
API,可以完成类似的操作。要在服务器上运行代码,我们使用
getServerSideProps
(请参阅:服务器端渲染 (SSR)

// pages/error/index.jsx

// this should run on the server
export async function getServerSideProps() {
  throw new Error("don't catch me for a 500 response");
  return { props: {} };
}

export default function Index() {
  return <h1>you should not see me</h1>;
}
© www.soinside.com 2019 - 2024. All rights reserved.