'Do I need to create a variable/object to return when catching an exception?
I have this way of handling exceptions for some time now, but lately has been bothering me.
protected function sendPostmarkBatch($envios_preparados)
{
try {
$client = new PostmarkClient($this->postmarkToken());
$sendResult = $client->sendEmailBatchWithTemplate($envios_preparados);
} catch (PostmarkException $e) {
log_message('error', 'HTTP: ' . $e->httpStatusCode . ' MESSAGE: ' . $e->message . ' ERROR CODE: ' . $e->postmarkApiErrorCode);
$sendResult = new stdClass();
$sendResult->ErrorCode = $e->postmarkApiErrorCode;
} catch (Exception $generalException) {
log_message('error', 'GENERAL EXCEPTION: ' . $generalException);
$sendResult = new stdClass();
$sendResult->ErrorCode = '1';
}
return $sendResult;
}
Is it really necessary to create the object or variable $sendResult at 'catch' to return it or it's already created even if 'try' fails? Is there a better way of doing it?
Thanks!
Solution 1:[1]
It's necessary.
I'm not sure if it's suits your logic, but you can do something like this:
protected function sendPostmarkBatch($envios_preparados)
{
$sendResult = new stdClass();
try {
$client = new PostmarkClient($this->postmarkToken());
$sendResult = $client->sendEmailBatchWithTemplate($envios_preparados);
} catch (PostmarkException $e) {
log_message('error', 'HTTP: ' . $e->httpStatusCode . ' MESSAGE: ' . $e->message . ' ERROR CODE: ' . $e->postmarkApiErrorCode);
$sendResult->ErrorCode = $e->postmarkApiErrorCode;
} catch (Exception $generalException) {
log_message('error', 'GENERAL EXCEPTION: ' . $generalException);
$sendResult->ErrorCode = '1';
}
return $sendResult;
}
If $client->sendEmailBatchWithTemplate($envios_preparados) fails, your $sendResult variable won't be overwrited.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | harmakit |
