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

Next.js App Router:生产环境如何获取API真实错误信息

生产环境下获取Server Action中API返回的真实错误信息

Next.js在生产环境会默认隐藏Server Components的具体错误详情,防止敏感信息泄露,但我们可以通过以下方式安全地获取并展示API返回的业务错误信息:

解决方案

1. 自定义安全错误类型

创建专属错误类,区分可暴露的业务错误和需隐藏的系统错误:

class SafeServerError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'SafeServerError';
  }
}

2. 修改Server Action的错误处理逻辑

在catch块中识别API返回的业务错误,包装为自定义SafeServerError抛出;系统错误则记录日志并返回通用提示:

export async function editIdeation({
  body
}: EditIdeationProps): Promise<EditIdeationResponse> {
  const token = getCookie();

  try {
    const data = await PATCH<EditIdeationBody, EditIdeationResponse>(
      url,
      token,
      "default",
      body
    );

    revalidatePath(url);

    return data;
  } catch (error: unknown) {
    if (error instanceof Error) {
      // 假设API返回的错误包含statusCode字段,4xx属于业务错误
      const apiError = error as any;
      if (apiError.statusCode && apiError.statusCode >= 400 && apiError.statusCode < 500) {
        throw new SafeServerError(apiError.message);
      } else {
        // 记录系统错误日志,便于排查
        console.error('Server Action系统错误:', error);
        throw new Error("An unknown error occurred");
      }
    } else {
      console.error('未知系统错误:', error);
      throw new Error("An unknown error occurred");
    }
  }
}

3. 配置Next.js允许暴露自定义错误

在next.config.js中添加配置,允许SafeServerError的错误信息在生产环境暴露:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverActions: {
      errorHandling: {
        allowList: ['SafeServerError'],
      },
    },
  },
};

module.exports = nextConfig;

4. 客户端捕获并展示错误

在客户端调用Server Action时,针对性捕获SafeServerError,展示真实业务错误信息:

async function handleSubmit(formData: FormData) {
  try {
    await editIdeation({ body: formData });
    // 提交成功后的逻辑
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'SafeServerError') {
      // 展示API返回的真实错误信息
      alert(error.message);
    } else {
      // 系统错误展示通用提示
      alert('操作失败,请稍后重试');
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:14:52