You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS 15调用notFound()无法全屏显示自定义404页面的问题

最优解决方法

方法:自定义NotFound错误,通过根error.js统一渲染全屏404

Next.js内置的notFound()会触发当前路由段的not-found.tsx,自动继承父级布局。要让所有调用场景都显示根目录的全屏404,可通过以下步骤实现:

  1. 创建自定义NotFound错误类
    在项目工具目录下新建错误文件,定义专属错误类型:

    // src/app/utils/errors.ts
    export class NotFoundError extends Error {
      constructor(message?: string) {
        super(message || '页面不存在');
        this.name = 'NotFoundError';
      }
    }
    
  2. 替换notFound()调用为抛出自定义错误
    在原来调用notFound()的方法中,改成抛出上面定义的错误:

    // src/app/(dashboard)/settings/states/_utils/routes.ts
    import { NotFoundError } from '@/app/utils/errors';
    
    export async function getStateById(id: string) {
      const state = await fetchState(id); // 你的数据获取逻辑
      if (!state) {
        // 替换notFound()为抛出自定义错误
        throw new NotFoundError();
      }
      return state;
    }
    
  3. 在根error.js中捕获并渲染全屏404
    根目录的error.tsx(无则新建)会捕获全局错误,判断错误类型后直接渲染根的自定义404组件:

    // src/app/error.tsx
    'use client';
    
    import { NotFoundError } from '@/app/utils/errors';
    import RootNotFound from './not-found';
    
    export default function Error({ error }: { error: Error }) {
      // 判断是否是自定义的NotFound错误
      if (error.name === 'NotFoundError') {
        return <RootNotFound />;
      }
    
      // 其他错误的默认处理
      return (
        <div className="flex h-screen items-center justify-center">
          <div className="text-center">
            <h2 className="text-2xl font-bold mb-4">出现未知错误</h2>
          </div>
        </div>
      );
    }
    

为什么这是最优解?

  • 无需在每个子路由目录下创建not-found.tsx,减少冗余代码
  • 保持URL不变(不会触发重定向),符合用户访问预期
  • 统一管理404逻辑,后续修改全屏404只需改动根目录的not-found.tsx
  • 不依赖复杂的上下文或布局判断,逻辑清晰直接

内容的提问来源于stack exchange,提问作者JG_GJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:33:14