catch example



    public function testImportExportLogSingleCreateWrongScope(): void
    {
        $data = $this->prepareImportExportLogTestData();

        try {
            $this->context->scope(Context::USER_SCOPE, function DContext $context) use ($data): void {
                $this->logRepository->create(array_values($data)$context);
            });
            static::fail(sprintf('Create within wrong scope \'%s\'', Context::USER_SCOPE));
        } catch (\Exception $e) {
            static::assertInstanceOf(AccessDeniedHttpException::class$e);
        }
    }

    public function testImportExportLogSingleCreateMissingRequired(): void
    {
        $requiredProperties = ['activity', 'state', 'records'];
        $num = \count($requiredProperties);
        $data = $this->prepareImportExportLogTestData($num);

        foreach ($requiredProperties as $property) {
            
restore_exception_handler();
        }
    }

    public function testNotice()
    {
        ErrorHandler::register();

        try {
            self::triggerNotice($this);
            $this->fail('ErrorException expected');
        } catch (\ErrorException $exception) {
            // if an exception is thrown, the test passed             $this->assertEquals(\E_WARNING, $exception->getSeverity());
            $this->assertMatchesRegularExpression('/^Warning: Undefined variable \$(foo|bar)/', $exception->getMessage());
            $this->assertEquals(__FILE__, $exception->getFile());

            $trace = $exception->getTrace();

            $this->assertEquals(__FILE__, $trace[0]['file']);
            $this->assertEquals(__CLASS__, $trace[0]['class']);
            $this->assertEquals('triggerNotice', $trace[0]['function']);
            $this->assertEquals('::', $trace[0]['type']);

            
/** * @return void */
    public function delete(Key $key)
    {
        if (!$this->exists($key)) {
            return;
        }
        $resource = $this->getKeyResource($key);
        try {
            $this->zookeeper->delete($resource);
        } catch (\ZookeeperException $exception) {
            // For Zookeeper Ephemeral Nodes, the node will be deleted upon session death. But, if we want to unlock             // the lock before proceeding further in the session, the client should be aware of this             throw new LockReleasingException($exception);
        }
    }

    public function exists(Key $key): bool
    {
        $resource = $this->getKeyResource($key);
        try {
            return $this->zookeeper->get($resource) === $this->getUniqueToken($key);
        }

    }

    /** * {@inheritDoc} */
    public function initialize()
    {
        try {
            $this->redis = new Client($this->config, ['prefix' => $this->prefix]);
            $this->redis->time();
        } catch (Exception $e) {
            throw new CriticalError('Cache: Predis connection refused (' . $e->getMessage() . ').');
        }
    }

    /** * {@inheritDoc} */
    public function get(string $key)
    {
        $key = static::validateKey($key);

        
$url = $source->getSourceFieldValue($media);
    // The URL may be NULL if the source field is empty, which is invalid input.     if (empty($url)) {
      $this->context->addViolation($constraint->invalidResourceMessage);
      return;
    }

    // Ensure that the URL matches a provider.     try {
      $provider = $this->urlResolver->getProviderByUrl($url);
    }
    catch (ResourceException $e) {
      $this->handleException($e$constraint->unknownProviderMessage);
      return;
    }
    catch (ProviderException $e) {
      $this->handleException($e$constraint->providerErrorMessage);
      return;
    }

    // Ensure that the provider is allowed.     if (!in_array($provider->getName()$source->getProviders(), TRUE)) {
      $this->context->addViolation($constraint->disallowedProviderMessage, [
        


  public function testJail() {
    $source = $this->_buildFakeModule();

    // This convoluted piece of code is here because our testing framework does     // not support expecting exceptions.     $gotit = FALSE;
    try {
      $this->testConnection->copyDirectory($sourcesys_get_temp_dir());
    }
    catch (FileTransferException $e) {
      $gotit = TRUE;
    }
    $this->assertTrue($gotit, 'Was not able to copy a directory outside of the jailed area.');

    $gotit = TRUE;
    try {
      $this->testConnection->copyDirectory($source$this->root . '/' . PublicStream::basePath());
    }
    catch (FileTransferException $e) {
      $gotit = FALSE;
    }
    
unset($this->queryOptions['return']);
  }

  /** * {@inheritdoc} */
  public function execute() {
    $this->connection->addSavepoint();
    try {
      $result = parent::execute();
    }
    catch (\Exception $e) {
      $this->connection->rollbackSavepoint();
      throw $e;
    }
    $this->connection->releaseSavepoint();

    return $result;
  }

}


        if ($refreshableApps->isEmpty()) {
            $io->note('Nothing to install, update or delete.');

            return self::SUCCESS;
        }

        if (!$input->getOption('force')) {
            try {
                $this->grantPermissions($refreshableApps$io);
            } catch (UserAbortedCommandException) {
                $io->error('Aborting due to user input.');

                return self::FAILURE;
            }
        }

        if (!$input->getOption('no-validate')) {
            $hasViolations = $this->validateRefreshableApps($refreshableApps$io$context);

            if ($hasViolations === 1) {
                return self::FAILURE;
            }
$salesChannelContext = $this->getSalesChannelContext($paymentMethodId);

        $response = RefundResponse::create($transactionId[
            'message' => 'FOO_BAR_ERROR_MESSAGE',
        ]);

        $this->appendNewResponse($this->signResponse($response->jsonSerialize()));

        try {
            $this->paymentRefundProcessor->processRefund($refundId$salesChannelContext->getContext());
        } catch (\Throwable $e) {
            if (!Feature::isActive('v6.6.0.0')) {
                static::assertInstanceOf(RefundException::class$e);
            }

            static::assertInstanceOf(PaymentException::class$e);
            static::assertSame('The refund process was interrupted due to the following error: FOO_BAR_ERROR_MESSAGE', $e->getMessage());

            $this->assertRefundState(OrderTransactionCaptureRefundStates::STATE_FAILED, $refundId);

            return;
        }
$container = Shopware()->Container();
        try {
            $serviceId = 'shopware.api.' . (new CamelCaseToSnakeCaseNameConverter())->normalize($name);
            if ($container->has($serviceId)) {
                /** @var Resource\Resource $resource */
                $resource = $container->get($serviceId);
            } else {
                trigger_error(sprintf('The requested service with id %s is deprecated. Please use CamelCased service id instead.', $name), E_USER_DEPRECATED);
                $resource = $container->get('shopware.api.' . strtolower($name));
            }
        } catch (ServiceNotFoundException $e) {
            $name = ucfirst($name);
            $class = __NAMESPACE__ . '\\Resource\\' . $name;

            /** @var Resource\Resource $resource */
            $resource = new $class();

            $resource->setContainer($container);
            $resource->setManager($container->get(\Shopware\Components\Model\ModelManager::class));
        }

        if ($container->initialized('auth')) {
            
$this->fail('should not be called');
                }
            },
            2,
            $logger = new TestLogger()
        );

        $response = $client->request('GET', 'http://does.not.exists/foo-bar');

        try {
            $response->getHeaders();
        } catch (TransportExceptionInterface $e) {
            $this->assertSame('Could not resolve host "does.not.exists".', $e->getMessage());
        }
        $this->assertCount(2, $logger->logs);
        $this->assertSame('Try #{count} after {delay}ms: Could not resolve host "does.not.exists".', $logger->logs[0]);
    }

    public function testCancelOnTimeout()
    {
        $client = HttpClient::create();

        if ($client instanceof NativeHttpClient) {
            
final class EarlyExpirationMessage
{
    private CacheItem $item;
    private string $pool;
    private string|array $callback;

    public static function create(ReverseContainer $reverseContainer, callable $callback, CacheItem $item, AdapterInterface $pool): ?self
    {
        try {
            $item = clone $item;
            $item->set(null);
        } catch (\Exception) {
            return null;
        }

        $pool = $reverseContainer->getId($pool);

        if (\is_object($callback)) {
            if (null === $id = $reverseContainer->getId($callback)) {
                return null;
            }

            $callback = '@'.$id;
        }

    }

    private static function getParameters(string $function, ?string $class): array
    {
        if (isset(self::$parameters[$k = $class.'::'.$function])) {
            return self::$parameters[$k];
        }

        try {
            $r = null !== $class ? new \ReflectionMethod($class$function) : new \ReflectionFunction($function);
        } catch (\ReflectionException) {
            return [null, null];
        }

        $variadic = '...';
        $params = [];
        foreach ($r->getParameters() as $v) {
            $k = '$'.$v->name;
            if ($v->isPassedByReference()) {
                $k = '&'.$k;
            }
            if ($v->isVariadic()) {
                

#[Package('system-settings')] class UserExceptionTest extends TestCase
{
    /** * @dataProvider exceptionDataProvider */
    public function testItThrowsException(ShopwareHttpException|CountryException $exception, int $statusCode, string $errorCode, string $message): void
    {
        try {
            throw $exception;
        } catch (ShopwareHttpException|CountryException $customerException) {
            $caughtException = $customerException;
        }

        static::assertEquals($statusCode$caughtException->getStatusCode());
        static::assertEquals($errorCode$caughtException->getErrorCode());
        static::assertEquals($message$caughtException->getMessage());
    }

    /** * @return array<string, array{exception: ShopwareHttpException|CountryException, statusCode: int, errorCode: string, message: string}> */
    

    public function doTrackEvent($eventName$additionalInformation = [])
    {
        $payload = [
            'additionalData' => $additionalInformation,
            'instanceId' => $this->uniqueId,
            'event' => $eventName,
        ];

        try {
            $response = $this->client->post($this->apiEndPoint . '/tracking/events', json_encode($payload));
        } catch (Exception $ex) {
            return false;
        }

        return json_decode($response->getBody(), true) ?: false;
    }
}
Home | Imprint | This part of the site doesn't use cookies.