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

Symfony 4.4异常/错误日志邮件发送失效问题排查

解决Symfony ExceptionListener中邮件发送不生效的问题

看起来你遇到的问题根源在于ExceptionListener的方法参数定义不符合Symfony事件监听器的规范,导致邮件发送逻辑根本没被执行。下面一步步帮你修正:

问题分析

在Symfony中,事件监听器的回调方法(比如onKernelException)的第一个参数必须是对应的事件对象(这里是ExceptionEvent),而且依赖的服务(比如EmailService)应该通过构造函数注入,而不是作为方法参数传递。你现在把EmailService放在了方法的第一个参数位置,Symfony无法正确识别这个方法为事件监听回调,所以当异常触发时,这个方法根本没被调用。

修正步骤

1. 修改ExceptionListener的构造函数和监听方法

更新ExceptionListener.php,把EmailService通过构造函数注入,同时修正onKernelException的参数顺序:

<?php
namespace App\EventListener;

use App\Service\EmailService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Psr\Log\LoggerInterface; // 可选,用来记录发送失败的日志

class ExceptionListener {
    private $em;
    private $emailService;
    private $logger; // 可选

    // 构造函数注入所需服务
    public function __construct(EntityManagerInterface $em, EmailService $emailService, LoggerInterface $logger) {
        $this->em = $em;
        $this->emailService = $emailService;
        $this->logger = $logger; // 可选
    }

    // 方法第一个参数必须是ExceptionEvent
    public function onKernelException(ExceptionEvent $event) {
        $exception = $event->getThrowable();
        $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        try {
            $this->emailService->sendLogToMail("myemail@gmail.com", $message);
        } catch (TransportExceptionInterface $e) {
            // 可选:记录发送失败的日志,方便排查
            $this->logger->error('Failed to send error log email: ' . $e->getMessage());
        }
    }
}

2. 确认services.yaml配置正确

你的监听器标签配置是对的,但如果添加了LoggerInterface,Symfony会自动注入对应的日志服务,不需要额外配置:

App\EventListener\ExceptionListener:
    tags:
        - { name: kernel.event_listener, event: kernel.exception }

验证修改

  1. 清除Symfony缓存(开发环境:php bin/console cache:clear)
  2. 再次访问TestController的index路由触发异常
  3. 检查邮箱是否收到错误日志邮件,如果还是没收到,可以查看日志文件(var/log/dev.log),看是否有邮件发送失败的日志信息

额外提示

  • 开发环境下,可以在try-catch中临时添加var_dump($e)来直观查看错误信息
  • 确保EmailService的sendLogToMail方法在构造函数注入后能正常工作(你已经在测试控制器验证过,所以这部分应该没问题)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:22:48