Next.js:静态站点生成(SSG)导出时如何捕获错误?
捕获Next.js静态导出过程中的所有错误
针对静态导出(next export)场景,除了getStaticProps里的try-catch,你可以通过以下几种方式覆盖组件渲染及其他环节的错误捕获:
1. 用React ErrorBoundary捕获组件渲染错误
React内置的ErrorBoundary可以捕获子组件树在渲染、生命周期方法以及构造函数中抛出的错误,包括静态导出时的页面渲染错误。
创建一个自定义ErrorBoundary组件:
class ExportErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { // 在这里记录错误日志,比如写入文件或上报 console.error("静态导出时组件渲染错误:", error, errorInfo); } render() { if (this.state.hasError) { // 导出时如果出错,可以返回一个占位组件,避免整个导出失败 return <div>页面渲染出错</div>; } return this.props.children; } } // React 18+ 也可以用函数组件版本 import { useErrorBoundary } from 'react-error-boundary'; function ExportErrorBoundary({ children }) { const { ErrorBoundary } = useErrorBoundary({ onError: (error, info) => { console.error("静态导出时组件渲染错误:", error, info); }, fallback: <div>页面渲染出错</div>, }); return <ErrorBoundary>{children}</ErrorBoundary>; }
然后在页面组件中用它包裹整个页面:
// pages/[slug].js export default function PostPage({ post }) { return ( <ExportErrorBoundary> <div> <h1>{post.title}</h1> {/* 可能抛出渲染错误的组件 */} <PostContent content={post.content} /> </div> </ExportErrorBoundary> ); }
2. 用next.config.js的onExportError钩子捕获全局导出错误
Next.js提供了onExportError配置项,在静态导出过程中发生任何错误(包括渲染错误、getStaticPaths/getStaticProps错误)时都会触发这个钩子,可以在这里统一处理错误日志:
// next.config.js module.exports = { async onExportError(error) { console.error("静态导出全局错误:", error); // 可以在这里执行错误上报、写入日志文件等操作 // 如果需要终止导出进程,可以抛出错误:throw error; }, };
3. 覆盖getStaticPaths的错误捕获
如果你的页面用了getStaticPaths,也要给它加上try-catch,避免路径生成时的错误导致整个导出失败:
export async function getStaticPaths() { try { const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); const paths = posts.map((post) => ({ params: { slug: post.slug } })); return { paths, fallback: false }; } catch (error) { console.error("getStaticPaths生成路径错误:", error); // 可以返回空路径或者默认路径,避免导出中断 return { paths: [], fallback: false }; } }
注意事项
- 静态导出时,ErrorBoundary的fallback组件会被渲染并导出为静态HTML,所以要确保fallback组件本身不会抛出错误。
onExportError是全局钩子,无论错误发生在哪个环节都会触发,适合做统一的错误日志收集。- 如果某个页面的错误无法被ErrorBoundary捕获(比如顶级组件的同步错误),可以在页面的默认导出函数外层包裹try-catch(仅适用于同步渲染错误)。
内容的提问来源于stack exchange,提问作者Trung Tran
相关产品推荐
相关产品推荐

