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

Next.js在Vercel生产环境中getServerSideProps抛错返回404而非500

问题:Vercel上Next.js的getServerSideProps抛出错误显示404而非500

我在Vercel生产环境搭建了基础的Next.js项目,使用getServerSideProps并集成Sentry错误日志,代码如下:

export const getServerSideProps = async () => {
  // some api call
 if(error) {
  throw new Error("Something went wrong")
}
  return {
    props: {
       data
    }
  };
};

自定义_error.js代码如下:

import * as Sentry from '@sentry/nextjs'
import { NextPageContext } from 'next'
import NextErrorComponent, { ErrorProps as NextErrorProps } from 'next/error'

const CustomErrorComponent = (props: NextErrorProps) => {
  return <NextErrorComponent statusCode={props.statusCode} />
}

CustomErrorComponent.getInitialProps = async (contextData: NextPageContext) => {
  await Sentry.captureUnderscoreErrorException(contextData)

  
  console.log(contextData.res?.statusCode) // this shows as 404
  console.log(contextData.err?.statusCode) // this as undefined

  return NextErrorComponent.getInitialProps(contextData)
}

export default CustomErrorComponent

本地运行相同生产构建时,能正确返回500: 'Internal Server Error',但在Vercel上却显示404: 'This page could not be found'。如何在Vercel上让该错误显示为500错误?


核心原因

Vercel对Next.js的错误处理逻辑有特殊规则:当getServerSideProps抛出未标记状态码的普通Error时,Vercel会默认返回404,而非Next.js本地环境的500。这是因为Vercel将未明确指定状态码的服务端错误归类为"页面不存在"场景。

解决步骤

  • 抛出带状态码的自定义错误
    修改getServerSideProps的错误抛出逻辑,给错误对象添加statusCode属性,明确标记为500错误:

    export const getServerSideProps = async () => {
      // some api call
      if (error) {
        const serverError = new Error("Something went wrong");
        // 手动添加状态码标识
        (serverError as any).statusCode = 500;
        throw serverError;
      }
      return {
        props: { data }
      };
    };
    
  • 在_error.js中强制设置响应状态码
    在自定义错误组件的getInitialProps中,检查错误对象并手动覆盖响应状态码,确保Vercel识别为500错误:

    CustomErrorComponent.getInitialProps = async (contextData: NextPageContext) => {
      await Sentry.captureUnderscoreErrorException(contextData);
    
      // 强制将服务端错误的响应状态码设为500
      if (contextData.err) {
        contextData.res?.statusCode = 500;
      }
    
      return NextErrorComponent.getInitialProps(contextData);
    };
    

本地与Vercel差异说明

Next.js本地开发/生产构建环境中,默认会将getServerSideProps抛出的任何错误视为500内部服务器错误;但Vercel部署环境对错误分类更严格,只有明确标记statusCode: 500的错误才会被识别为500,否则会 fallback 到404。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:35:21