TransportException example



        $endpoint = sprintf('https://%s/bot%s/%s', $this->getEndpoint()$this->token, $this->getPath($options));

        $response = $this->client->request('POST', $endpoint[
            'json' => array_filter($options),
        ]);

        try {
            $statusCode = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            throw new TransportException('Could not reach the remote Telegram server.', $response, 0, $e);
        }

        if (200 !== $statusCode) {
            $result = $response->toArray(false);

            throw new TransportException('Unable to '.$this->getAction($options).' the Telegram message: '.$result['description'].sprintf(' (code %d).', $result['error_code'])$response);
        }

        $success = $response->toArray(false);

        $sentMessage = new SentMessage($message(string) $this);
        

    public function send(string $body, array $headers, int $delay = 0): string
    {
        $message = json_encode([
            'body' => $body,
            'headers' => $headers,
        ]);

        if (false === $message) {
            throw new TransportException(json_last_error_msg());
        }

        try {
            $job = $this->client->useTube($this->tube)->put(
                $message,
                PheanstalkInterface::DEFAULT_PRIORITY,
                $delay / 1000,
                $this->ttr
            );
        } catch (Exception $exception) {
            throw new TransportException($exception->getMessage(), 0, $exception);
        }
 else {
            $this->error = $error;
            $this->errorMessage = $error->getMessage();
        }
    }

    public function isTimeout(): bool
    {
        $this->didThrow = true;

        if (null !== $this->error) {
            throw new TransportException($this->errorMessage, 0, $this->error);
        }

        return true;
    }

    public function isFirst(): bool
    {
        $this->didThrow = true;
        throw null !== $this->error ? new TransportException($this->errorMessage, 0, $this->error) : new TimeoutException($this->errorMessage);
    }

    
'json' => [
                'from' => $from,
                'to' => $message->getPhone(),
                'text' => $message->getSubject(),
                'messaging_profile_id' => $this->messagingProfileId ?? '',
            ],
        ]);

        try {
            $statusCode = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            throw new TransportException('Could not reach the remote Telnyx server.', $response, 0, $e);
        }

        if (200 !== $statusCode) {
            $error = $response->toArray(false);
            if (!isset($error['errors'])) {
                throw new TransportException('Unable to send the SMS.', $response);
            }

            throw new TransportException('Unable to send the SMS: '.$error['errors'][0]['detail'] ?? 'Unknown reason', $response);
        }

        
// these headers can't be overwritten according to Sendgrid docs         // see https://sendgrid.api-docs.io/v3.0/mail-send/mail-send-errors#-Headers-Errors         $headersToBypass = ['x-sg-id', 'x-sg-eid', 'received', 'dkim-signature', 'content-transfer-encoding', 'from', 'to', 'cc', 'bcc', 'subject', 'content-type', 'reply-to'];
        foreach ($email->getHeaders()->all() as $name => $header) {
            if (\in_array($name$headersToBypass, true)) {
                continue;
            }

            if ($header instanceof TagHeader) {
                if (10 === \count($categories)) {
                    throw new TransportException(sprintf('Too many "%s" instances present in the email headers. Sendgrid does not accept more than 10 categories on an email.', TagHeader::class));
                }
                $categories[] = mb_substr($header->getValue(), 0, 255);
            } elseif ($header instanceof MetadataHeader) {
                $customArguments[$header->getKey()] = $header->getValue();
            } else {
                $payload['headers'][$header->getName()] = $header->getBodyAsString();
            }
        }

        if (\count($categories) > 0) {
            $payload['categories'] = $categories;
        }
if (!isset($options['normalized_headers']['content-type']) && 0 !== ($curlopts[\CURLOPT_INFILESIZE] ?? null)) {
                    $curlopts[\CURLOPT_HTTPHEADER][] = 'Content-Type: application/x-www-form-urlencoded';
                }
            }
        } elseif ('' !== $body || 'POST' === $method) {
            $curlopts[\CURLOPT_POSTFIELDS] = $body;
        }

        if ($options['peer_fingerprint']) {
            if (!isset($options['peer_fingerprint']['pin-sha256'])) {
                throw new TransportException(__CLASS__.' supports only "pin-sha256" fingerprints.');
            }

            $curlopts[\CURLOPT_PINNEDPUBLICKEY] = 'sha256//'.implode(';sha256//', $options['peer_fingerprint']['pin-sha256']);
        }

        if ($options['bindto']) {
            if (file_exists($options['bindto'])) {
                $curlopts[\CURLOPT_UNIX_SOCKET_PATH] = $options['bindto'];
            } elseif (!str_starts_with($options['bindto'], 'if!') && preg_match('/^(.*):(\d+)$/', $options['bindto']$matches)) {
                $curlopts[\CURLOPT_INTERFACE] = $matches[1];
                $curlopts[\CURLOPT_LOCALPORT] = $matches[2];
            }
$headers['X-Ovh-Consumer'] = $this->consumerKey;
        $headers['X-Ovh-Signature'] = '$1$'.sha1($toSign);

        $response = $this->client->request('POST', $endpoint[
            'headers' => $headers,
            'body' => $body,
        ]);

        try {
            $statusCode = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            throw new TransportException('Could not reach the remote OvhCloud server.', $response, 0, $e);
        }

        if (200 !== $statusCode) {
            $error = $response->toArray(false);

            throw new TransportException(sprintf('Unable to send the SMS: %s.', $error['message'])$response);
        }

        $success = $response->toArray(false);

        if (!isset($success['ids'][0])) {
            


        $endpoint = sprintf('https://%s/v1/Account/%s/Message/', $this->getEndpoint()$this->authId);
        $response = $this->client->request('POST', $endpoint[
            'auth_basic' => [$this->authId, $this->authToken],
            'json' => array_filter($options),
        ]);

        try {
            $statusCode = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            throw new TransportException('Could not reach the remote Plivo server.', $response, 0, $e);
        }

        if (202 !== $statusCode) {
            try {
                $error = $response->toArray(false);
            } catch (JsonException) {
                $error['error'] = $response->getContent(false);
            }
            throw new TransportException(sprintf('Unable to send the SMS - status code: "%s": "%s".', $statusCode$error['error'] ?? 'unknown error')$response);
        }

        
'clientId' => uniqid(),
                    ],
                ],
                'login' => $this->login,
                'password' => $this->password,
            ],
        ]);

        try {
            $result = $response->toArray(false);
        } catch (TransportExceptionInterface $e) {
            throw new TransportException('Could not reach the remote Iqsms server.', $response, 0, $e);
        }

        foreach ($result['messages'] as $msg) {
            if ('accepted' !== $msg['status']) {
                throw new TransportException(sprintf('Unable to send the SMS: "%s".', $msg['status'])$response);
            }
        }

        $message = new SentMessage($message(string) $this);
        $message->setMessageId($result['messages'][0]['smscId']);

        


        $requestOptions = $response->getRequestOptions();
        $this->assertFalse(isset($requestOptions['normalized_headers']['content-length']));
    }

    public function testThrowExceptionInBodyGenerator()
    {
        $mockHttpClient = new MockHttpClient([
            new MockResponse((static function D): \Generator {
                yield 'foo';
                throw new TransportException('foo ccc');
            })()),
            new MockResponse((static function D): \Generator {
                yield 'bar';
                throw new \RuntimeException('bar ccc');
            })()),
        ]);

        try {
            $mockHttpClient->request('GET', 'https://symfony.com', [])->getContent();
            $this->fail();
        } catch (TransportException $e) {
            
$t->send(new RawMessage(''));
        $this->assertTransports($t, 1, []);
        $t->send(new RawMessage(''));
        $this->assertTransports($t, 1, []);
        $t->send(new RawMessage(''));
        $this->assertTransports($t, 1, []);
    }

    public function testSendAllDead()
    {
        $t1 = $this->createMock(TransportInterface::class);
        $t1->expects($this->once())->method('send')->will($this->throwException(new TransportException()));
        $t2 = $this->createMock(TransportInterface::class);
        $t2->expects($this->once())->method('send')->will($this->throwException(new TransportException()));
        $t = new FailoverTransport([$t1$t2]);
        $this->expectException(TransportException::class);
        $this->expectExceptionMessage('All transports failed.');
        $t->send(new RawMessage(''));
        $this->assertTransports($t, 0, [$t1$t2]);
    }

    public function testSendOneDead()
    {
        
$options['to'] = $message->getPhone();
        $options['msg'] = $message->getSubject();

        $endpoint = sprintf('https://%s/api/light/diffusions/sms', $this->getEndpoint());
        $response = $this->client->request('POST', $endpoint[
            'query' => array_filter($options),
        ]);

        try {
            $statusCode = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            throw new TransportException('Could not reach the remote Contact Everyone server.', $response, 0, $e);
        }

        if (200 !== $statusCode) {
            $error = $response->toArray(false);
            throw new TransportException(sprintf('Unable to send the Contact Everyone message with following error: "%s". For further details, please check this logId: "%s".', $error['message']$error['logId'])$response);
        }

        $result = $response->getContent(false);

        $sentMessage = new SentMessage($message(string) $this);
        $sentMessage->setMessageId($result ?? '');

        


    private function addPostmarkHeaders(Message $message): void
    {
        $message->getHeaders()->addTextHeader('X-PM-KeepID', 'true');

        $headers = $message->getHeaders();

        foreach ($headers->all() as $name => $header) {
            if ($header instanceof TagHeader) {
                if ($headers->has('X-PM-Tag')) {
                    throw new TransportException('Postmark only allows a single tag per email.');
                }

                $headers->addTextHeader('X-PM-Tag', $header->getValue());
                $headers->remove($name);
            }

            if ($header instanceof MetadataHeader) {
                $headers->addTextHeader('X-PM-Metadata-'.$header->getKey()$header->getValue());
                $headers->remove($name);
            }
        }

        

        $this->response = $client->request($method$url['buffer' => false] + $options);
        $this->passthru = $passthru;
        $this->initializer = static function Dself $response, float $timeout = null) {
            if (null === $response->shouldBuffer) {
                return false;
            }

            while (true) {
                foreach (self::stream([$response]$timeout) as $chunk) {
                    if ($chunk->isTimeout() && $response->passthru) {
                        foreach (self::passthru($response->client, $responsenew ErrorChunk($response->offset, new TransportException($chunk->getError()))) as $chunk) {
                            if ($chunk->isFirst()) {
                                return false;
                            }
                        }

                        continue 2;
                    }

                    if ($chunk->isFirst()) {
                        return false;
                    }
                }
protected static function perform(ClientState $multi, array &$responses): void
    {
        foreach ($responses as $response) {
            $id = $response->id;

            if (!isset($response->body)) {
                // Canceled response                 $response->body = [];
            } elseif ([] === $response->body) {
                // Error chunk                 $multi->handlesActivity[$id][] = null;
                $multi->handlesActivity[$id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
            } elseif (null === $chunk = array_shift($response->body)) {
                // Last chunk                 $multi->handlesActivity[$id][] = null;
                $multi->handlesActivity[$id][] = array_shift($response->body);
            } elseif (\is_array($chunk)) {
                // First chunk                 try {
                    $offset = 0;
                    $chunk[1]->getStatusCode();
                    $chunk[1]->getHeaders(false);
                    self::readResponse($response$chunk[0]$chunk[1]$offset);
                    
Home | Imprint | This part of the site doesn't use cookies.