How do I handle the errors in sending emails? I've tried to wrap the calling function with try catch but it is still printing the json error: e.g.
[
{
"message": "Each email address in the personalization block should be unique between to, cc, and bcc. We found the first duplicate instance of [[email protected]] in the personalizations.0.cc field.",
"field": "personalizations.0",
"help": "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.recipient-errors"
}
]
I don't want the library to print these errors instead I'd like to handle it.
I also are having an issue handling these, I would like to catch these errors and be able to return the error message to our logging systems.
Hello @jaimehing, @KnightAR,
try {
$response = $sendgrid->client->mail()->send()->post($mail);
} catch (Exception $e) {
// Handle Exception
}
Does that help?
Hi @thinkingserious. nope. that's the thing I've tried and it's being forced to return the error json response
Hi @jaimehing,
I'm not sure what you mean by "being forced to return the error json". Can you please provide some code to help provide some context?
Thanks!
@thinkingserious When CURL occurs a 400 error message, it does not return the body and sends the body to STDERR instead. The work around would be to set a HTTP 200 Alias to 400 and set CURLOPT_FAILONERROR to false. However, I couldn't get it working.
@KnightAR,
Ah, thanks! Looks like we will need to make the adjustment here: https://github.com/sendgrid/php-http-client/blob/master/lib/Client.php#L144
I'm classifying this as a bug and putting it on our backlog for a fix.
@jaimehing @thinkingserious With the recent update, I got it working by doing the following:
$sg = new \SendGrid($sendgridkey, [], array(
CURLOPT_FAILONERROR => false,
CURLOPT_HTTP200ALIASES => [400],
CURLOPT_VERBOSE => false
));
var_dump(json_decode($response->body()));
As a test, I did an invalid request and got a propery json body:
class stdClass#72 (1) {
public $errors =>
array(1) {
[0] =>
class stdClass#71 (3) {
public $message =>
string(45) "Invalid type. Expected: object, given: array."
public $field =>
string(26) "mail_settings.sandbox_mode"
public $help =>
string(101) "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.mail_settings.sandbox_mode"
}
}
Thanks for the help
@KnightAR,
Thanks for circling back with the solution! Please fill out this form and we will send you some swag.
@KnightAR What recent update are you talking about ? Sendgrid constructor (master or tags) doesn't have a third parameter.
public function __construct($apiKey, $options = array())
This has been moved here.