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

如何处理Laravel中向不存在的邮箱发信时抛出的异常错误?

问题根因
  • 现有代码仅捕获了JWTException类型的异常,你用的旧版Mail组件底层依赖SwiftMailer库,当收件邮箱不存在时抛出的是Swift_TransportException异常,该异常没有被捕获导致程序直接报错退出。
  • 异常抛出后代码中断执行,不会走到后续Mail::failures()的判断逻辑,因此你预设的重定向和错误提示逻辑没有触发。
修复代码

首先在文件顶部引入需要捕获的异常类:

use Swift_TransportException;
use Exception;

修改后的业务逻辑代码如下:

// 建议将佣金记录删除逻辑放在此处,保证无论邮件是否发送成功,驳回后的核心业务逻辑先执行
// 此处写你删除佣金记录的代码

try { 
    // email sending actual part here
    Mail::send([], [], function($message)use($data) {
        $message->from($data['from'])
            ->to($data["email"])
            ->subject($data["subject"])
            ->setBody($data["messages"], 'text/html');
        });
} catch(JWTException $exception){
    $this->serverstatuscode = "0";
    $this->serverstatusdes = $exception->getMessage();
} catch(Swift_TransportException $exception) {
    // 捕获邮件传输类错误,比如收件人不存在、服务器连接失败等
    $this->statusdesc  = "Error sending mail";
    $this->statuscode  = "0";
    return redirect()->route('voyager.dashboard')
    ->with([
        'message'    => "Commission is rejected but fail to send email",
        'alert-type' => 'warning',
    ]);
} catch(Exception $exception) {
    // 兜底捕获其他未知异常,避免程序直接报错
    $this->statusdesc  = "Error sending mail";
    $this->statuscode  = "0";
    return redirect()->route('voyager.dashboard')
    ->with([
        'message'    => "Commission is rejected but fail to send email",
        'alert-type' => 'warning',
    ]);
}
    
if(Mail::failures()) {
    $this->statusdesc  =   "Error sending mail";
    $this->statuscode  =   "0";
    return redirect()->route('voyager.dashboard')
    ->with([
        'message'    => "Commission is rejected but fail to send email",
        'alert-type' => 'warning',
    ]);
} else {
    return redirect()->back()
    ->with([
        'message'    => "Commission is rejected and comment is sent via email successfully",
        'alert-type' => 'success',
    ]);
}
修改说明
  • 新增Swift_TransportException异常捕获分支,专门处理邮件传输相关的错误,完美覆盖你遇到的收件人不存在报错场景
  • 新增通用Exception兜底捕获,避免其他未预见的异常直接抛出到前端
  • 保留了你原有的所有交互逻辑,错误提示和跳转规则完全符合你的需求
  • 额外建议将佣金记录删除逻辑移到邮件发送前执行,避免邮件发送失败导致核心的驳回业务逻辑没有落地

内容的提问来源于stack exchange,提问作者Tan Si Kai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:15:03