【问题标题】:How to throw a 500 error from getStaticProps如何从 getStaticProps 抛出 500 错误
【发布时间】:2022-02-16 00:11:51
【问题描述】:

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

这可能来自 getStaticProps 吗?

【问题讨论】:

    标签: next.js


    【解决方案1】:

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

    ❌ 不要在getStaticProps 中添加try {} catch(){}

    ✅ 这样做:

    export async function getServerSideProps() {
      throw new TypeError("Ops, CMS didn't return a reasonable response.");
    }
    

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


    在开发中,调用堆栈会出现错误,以了解错误的来源。

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

    yarn build && NODE_ENV=production yarn start
    

    ⚠️ 每次更新代码时都重新运行此命令,否则您将看不到任何更改。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2018-06-25
      相关资源
      最近更新 更多