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

Symfony 6+FosRestBundle:生产环境禁用异常堆栈追踪

解决Symfony 6 + FOSRestBundle生产环境显示异常堆栈追踪问题

1. 确认生产环境的APP_DEBUG已关闭

首先确保生产环境下的APP_DEBUG环境变量设置为false(对应.env.prod文件里的APP_DEBUG=0),内核初始化依赖这个参数控制调试模式:

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);

若生产环境APP_DEBUG为true,即便配置了FOSRest的异常处理,仍会显示完整堆栈信息。

2. 完善FOSRestBundle的异常处理配置

在fos_rest配置中扩展exception节点,添加disable_stacktrace和messages配置,强制生产环境隐藏堆栈追踪,仅返回错误消息:

fos_rest:
  # 保留原有配置内容
  body_listener: true
  body_converter:
    enabled: true
    validate: true
    validation_errors_argument: violations
  view:
    formats: { json: true, xml: false, rss: false }
    view_response_listener: true
  serializer:
    serialize_null: true
  format_listener:
    rules:
      - { path: '^/api', priorities: ['json'], fallback_format: 'json', prefer_extension: true }
      - { path: '^/publicapi', priorities: ['json'], fallback_format: 'json', prefer_extension: true }
      - { path: '^/', priorities: ['html'], fallback_format: 'html' }
  param_fetcher_listener: force
  
  # 完善异常处理配置
  exception:
    enabled: true
    disable_stacktrace: true # 禁用堆栈追踪输出
    messages:
      'Symfony\Component\Exception\Throwable': true # 仅返回异常消息内容
    codes:
      'Symfony\Component\Security\Core\Exception\BadCredentialsException': 401
      'Symfony\Component\Security\Core\Exception\InvalidArgumentException': 400

补充说明

  • disable_stacktrace: true会直接关闭堆栈信息输出,若需要区分环境控制,可在config/packages/prod/fos_rest.yaml中单独设置该参数。
  • 若需更精细化的异常响应,可自定义异常控制器,但上述配置已能解决生产环境暴露堆栈的核心问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:00:09