如何从 getStaticProps 抛出 500 错误

gra*_*ury 3 next.js

我有一个 Nextjs 应用程序。我从无头 CMS 获取数据来填充 404 错误页面。如果我没有从 CMS 得到合理的响应,我会抛出 500 错误。

这可以通过 getStaticProps 实现吗?

a.b*_*eri 12

只需抛出错误,NextJS 就会为您生成 500。

\n

\xe2\x9d\x8c 不要try {} catch(){}getStaticProps.

\n

\xe2\x9c\x85 执行此操作:

\n
export async function getServerSideProps() {\n  throw new TypeError("Ops, CMS didn\'t return a reasonable response.");\n}\n
Run Code Online (Sandbox Code Playgroud)\n

请注意:错误组件仅在生产中使用。

\n
\n

在开发过程中,您\xe2\x80\x99将收到调用堆栈的错误,以了解错误源自何处。

\n

如果您想在部署到生产环境之前查看会发生什么,可以在本地环境中运行以下命令:

\n
yarn build && NODE_ENV=production yarn start\n
Run Code Online (Sandbox Code Playgroud)\n

\xe2\x9a\xa0\xef\xb8\x8f 每次更新代码时重新运行此命令,否则您将看不到任何更改。

\n

请参阅https://nextjs.org/docs/advanced-features/custom-error-page#more-advanced-error-page-customizing

\n