Answer the question
In order to leave comments, you need to log in
Doesn't handle try\catch correctly. How to fix?
Hello.
With exceptions both within PHPMailer and PHP, one can say it didn’t work (I heard it, but I didn’t use it), so don’t judge strictly if I make some banal mistake.
I got on the toaster, because my head is already swollen, from the information that I read about exceptions and I seem to be doing everything as recommended, but it still doesn’t work out to do what is required.
The bottom line is, I use PHPMailer to send letters, the mailing works, now it is necessary to wrap up checks, "some stages of work" ( probably it would be more correct to put it this way ): sending letters, checking the included letter template, correctness of the received data, etc.
I skid on creating a check when sending a letter. mailer->send();
The course of action is as follows:
1. I create my own class EmailSendingFailed, inherit from Exception
<?php declare(strict_types=1);
namespace extMailer;
use Exception;
class EmailSendingFailed extends Exception {}
namespace extMailer;
use EmailSendingFailed;
...
//В методе отвечающим за отправку реализую try\catch
public function sending(string $event, EmailAddress $recipient, array $tpl = array()): void
{
$this->mailer->addAddress($recipient->email, $recipient->name);
$this->mailer->Subject = $subject;
$this->mailer->Body = $body;
$this->mailer->isHTML(true);
try {
if (!$this->mailer->send()) {
throw new EmailSendingFailed("Couldn't send email. Invalid sender address '{$recipient->email}'.");
}
} catch (Exception $e) {
$e->getMessage();
}
$this->mailer->ClearAddresses();
}
Answer the question
In order to leave comments, you need to log in
So you've caught the error, but you're not displaying it.
You still have code after the try-catch, so it's being executed.
UPD. This is what your method should look like
<?php
public function sending(string $event, EmailAddress $recipient, array $tpl = array()): void
{
try {
$this->mailer->addAddress($recipient->email, $recipient->name);
$this->mailer->Subject = $subject;
$this->mailer->Body = $body;
$this->mailer->isHTML(true);
if (!$this->mailer->send()) {
throw new EmailSendingFailed("Couldn't send email. Invalid sender address '{$recipient->email}'.");
}
return ['status' => 'success'];
$this->mailer->ClearAddresses();
} catch (Exception $e) {
return ['status' => 'error', 'error_message' => $e->getMessage();];
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question