如何让Next.js仅在测试环境显示完整错误而非模糊提示?
解决Next.js测试环境生产构建后错误信息模糊的问题
核心思路
通过环境变量区分环境,在测试/验收环境的生产构建中保留并展示完整错误信息,生产环境仍保持模糊提示以避免敏感信息泄露。
步骤1:配置环境变量
创建环境配置文件:
- 项目根目录新建
.env.test(测试环境):NEXT_PUBLIC_APP_ENV=test - 新建
.env.staging(验收环境):NEXT_PUBLIC_APP_ENV=staging - 生产环境的
.env.production保持:NEXT_PUBLIC_APP_ENV=production
- 项目根目录新建
更新package.json的构建脚本,指定对应环境的配置文件:
{ "scripts": { "build:test": "next build --env-file=.env.test", "build:staging": "next build --env-file=.env.staging", "build:prod": "next build --env-file=.env.production" } }
步骤2:修改error.tsx组件
在error.tsx中根据环境变量控制错误展示逻辑,仅在测试/验收环境显示完整堆栈和错误信息:
'use client'; import { useEffect, useState } from 'react'; export default function Error({ error, reset }: { error: Error & { digest?: string }, reset: () => void }) { const [fullError, setFullError] = useState<Error | null>(null); useEffect(() => { // 仅在非生产环境存储完整错误 if (process.env.NEXT_PUBLIC_APP_ENV !== 'production') { setFullError(error); } }, [error]); // 测试/验收环境展示完整错误 if (process.env.NEXT_PUBLIC_APP_ENV !== 'production' && fullError) { return ( <div className="p-6"> <h2 className="text-red-600 text-xl mb-4">组件抛出异常</h2> <p className="mb-3"><strong>错误详情:</strong> {fullError.message}</p> {fullError.stack && ( <pre className="bg-gray-50 p-4 rounded-md overflow-auto max-h-72 text-sm"> {fullError.stack} </pre> )} <button onClick={reset} className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700" > 重试操作 </button> </div> ); } // 生产环境显示模糊提示 return ( <div className="p-6 text-center"> <h2 className="text-red-600 text-xl mb-4">发生意外错误</h2> <p>为避免泄露敏感信息,生产构建中省略具体消息。</p> <button onClick={reset} className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700" > 重试操作 </button> </div> ); }
步骤3:开启测试环境的源码映射(可选)
在next.config.js中配置,仅在非生产环境生成浏览器源码映射,方便测试人员定位到具体代码行:
/** @type {import('next').NextConfig} */ const nextConfig = { // 仅测试/验收环境开启生产源码映射 productionBrowserSourceMaps: process.env.NEXT_PUBLIC_APP_ENV !== 'production', }; module.exports = nextConfig;
注意事项
- 确保测试/验收环境的构建脚本正确加载对应环境变量,避免误配置为生产环境。
- 生产环境必须保持
NEXT_PUBLIC_APP_ENV=production,防止敏感错误信息泄露给用户。
内容的提问来源于stack exchange,提问作者SneepSnoop
相关产品推荐
相关产品推荐

