gpt4 book ai didi

javascript - 如何干净地处理 nextjs getStaticProps 中的错误

转载 作者:行者123 更新时间:2023-12-05 00:30:02 28 4
gpt4 key购买 nike

我现在非常忙于构建我的第一个 Next.JS 应用程序(Next 和 Strapi)。现在一切正常,但我很好奇在使用 getStaticProps 时实现错误处理的最佳方法是什么? .
我自己尝试了一些事情(传递多个 Prop 等,但这一切都不起作用(典型的非序列化 JSON 错误)。我想要实现的是页面本身(例如/about)上没有找到数据的错误消息. 附有错误消息(statusCode)。
我希望这是可能的,我做了很多研究,发现:https://github.com/vercel/next.js/pull/17755这个。但这并不是我想要的。

最佳答案

您可以创建custom 404 and 500 error pages .有一个选项可以显示 statusCode但是,您可以通过返回 notfound: true 来告诉 Next 使用 404 页面。在 getStaticProps .
如果您返回 notfound: true ,statusCode会一直显示404页面,你知道statuscode会是404。
以下是在 getStaticProps 中捕获错误的示例- 这将生成您的页面或显示根据您的规范设计的自定义错误页面。

export const getStaticProps = async () => {
try {
const { data, errors } = await someQuery();
if (errors || !data) {
return { notFound: true };
}
return { props: { data } };
} catch () {
return { notFound: true };
}
};
notFound 的一个不那么明显的附加用例是使用它从生产中排除目录或页面。以下检查将在下一个/导出 (SSG) 期间跳过整个页面或目录。此检查用于生成仅用于开发的静态页面。
如果目录中的单个页面具有以下检查,则在构建过程中将跳过该页面。如果目录中的每个页面都有检查 - 将跳过整个目录,包括文件夹。
export const getStaticProps = async () => {
if (process.env.NODE_ENV === 'production') {
return { notFound: true };
}
...
};
确保您不包含您不希望在 getStaticPaths 中内置的路线也。

关于javascript - 如何干净地处理 nextjs getStaticProps 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67168743/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com