HttpException example

// We need to return the part of the form (or some other content) that needs     // to be re-rendered so the browser can update the page with changed     // content. It is up to the #ajax['callback'] function of the element (may     // or may not be a button) that triggered the Ajax request to determine what     // needs to be rendered.     $callback = NULL;
    if (($triggering_element = $form_state->getTriggeringElement()) && isset($triggering_element['#ajax']['callback'])) {
      $callback = $triggering_element['#ajax']['callback'];
    }
    $callback = $form_state->prepareCallback($callback);
    if (empty($callback) || !is_callable($callback)) {
      throw new HttpException(500, 'The specified #ajax callback is empty or not callable.');
    }
    $result = call_user_func_array($callback[&$form, &$form_state$request]);

    // If the callback is an #ajax callback, the result is a render array, and     // we need to turn it into an AJAX response, so that we can add any commands     // we got earlier; typically the UpdateBuildIdCommand when handling an AJAX     // submit from a cached page.     if ($result instanceof AjaxResponse) {
      $response = $result;
    }
    else {
      
$this->assertTrue($event->isAllowingCustomResponseCode());

        $this->assertEquals('Forbidden', $event->getResponse()->getContent());
        $this->assertEquals(403, $event->getResponse()->getStatusCode());
        $this->assertSame($exception$event->getThrowable());
    }

    public static function getAuthenticationExceptionProvider()
    {
        return [
            [$e = new AuthenticationException()new HttpException(Response::HTTP_UNAUTHORIZED, '', $e[], 0)],
            [new \LogicException('random', 0, $e = new AuthenticationException())new HttpException(Response::HTTP_UNAUTHORIZED, '', $e[], 0)],
            [new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AuthenticationException()))new HttpException(Response::HTTP_UNAUTHORIZED, 'embed', $e[], 0)],
            [new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AccessDeniedException()))new HttpException(Response::HTTP_UNAUTHORIZED, 'embed', $e[], 0)],
            [$e = new AuthenticationException('random', 0, new \LogicException())new HttpException(Response::HTTP_UNAUTHORIZED, 'random', $e[], 0)],
        ];
    }

    /** * This test should be removed in Symfony 7.0 when adding native return types to AuthenticationEntryPointInterface::start(). * * @group legacy */
$this->createMock(EntityCacheKeyGenerator::class),
            $this->createMock(CacheInvalidator::class),
            new EventDispatcher()
        );

        $request = new Request();

        $event = new ExceptionEvent(
            $this->createMock(Kernel::class),
            $request,
            0,
            new HttpException(Response::HTTP_NOT_FOUND)
        );
        $subscriber->onError($event);

        /** @var StorefrontResponse $response */
        $response = $event->getResponse();

        static::assertInstanceOf(Response::class$response);
        static::assertInstanceOf(StorefrontResponse::class$response);
        static::assertEmpty($response->getData());
        static::assertNull($response->getContext());
    }

    
public function testHeadersDefault()
    {
        $exception = $this->createException();
        $this->assertSame([]$exception->getHeaders());
    }

    /** * @dataProvider headerDataProvider */
    public function testHeadersConstructor($headers)
    {
        $exception = new HttpException(200, '', null, $headers);
        $this->assertSame($headers$exception->getHeaders());
    }

    /** * @dataProvider headerDataProvider */
    public function testHeadersSetter($headers)
    {
        $exception = $this->createException();
        $exception->setHeaders($headers);
        $this->assertSame($headers$exception->getHeaders());
    }

  public function onMaintenanceModeRequest(RequestEvent $event) {
    $request = $event->getRequest();

    if ($request->getRequestFormat() !== 'api_json') {
      return;
    }
    // Retry-After will be random within a range defined in jsonapi settings.     // The goals are to keep it short and to reduce the thundering herd problem.     $header_settings = $this->config->get('jsonapi.settings')->get('maintenance_header_retry_seconds');
    $retry_after_time = rand($header_settings['min']$header_settings['max']);
    $http_exception = new HttpException(503, $this->maintenanceMode->getSiteMaintenanceMessage());
    $document = new JsonApiDocumentTopLevel(new ErrorCollection([$http_exception])new NullIncludedData()new LinkCollection([]));
    $response = new ResourceResponse($document$http_exception->getStatusCode()[
      'Content-Type' => 'application/vnd.api+json',
      'Retry-After' => $retry_after_time,
    ]);
    // Calling RequestEvent::setResponse() also stops propagation of event.     $event->setResponse($response);
  }

}
return ['api_json'];
  }

  /** * {@inheritdoc} */
  public function onException(ExceptionEvent $event) {
    if (!$this->isJsonApiExceptionEvent($event)) {
      return;
    }
    if (($exception = $event->getThrowable()) && !$exception instanceof HttpException) {
      $exception = new HttpException(500, $exception->getMessage()$exception);
      $event->setThrowable($exception);
    }

    $this->setEventResponse($event$exception->getStatusCode());
  }

  /** * {@inheritdoc} */
  protected function setEventResponse(ExceptionEvent $event$status) {
    /** @var \Symfony\Component\HttpKernel\Exception\HttpException $exception */
    

  public function handleFileUploadForField(FieldDefinitionInterface $field_definition$filename, AccountInterface $owner) {
    assert(is_a($field_definition->getClass(), FileFieldItemList::class, TRUE));
    $settings = $field_definition->getSettings();
    $destination = $this->getUploadLocation($settings);

    // Check the destination file path is writable.     if (!$this->fileSystem->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
      throw new HttpException(500, 'Destination file path is not writable');
    }

    $validators = $this->getUploadValidators($field_definition);

    $prepared_filename = $this->prepareFilename($filename$validators);

    // Create the file.     $file_uri = "{$destination}/{$prepared_filename}";
    if ($destination === $settings['uri_scheme'] . '://') {
      $file_uri = "{$destination}{$prepared_filename}";
    }

    
'/400/c', RecordFactory::create(Logger::ERROR, context: self::getContextException(400)), true],
            ['/401',   RecordFactory::create(Logger::ERROR, context: self::getContextException(401)), true],
            ['/403',   RecordFactory::create(Logger::ERROR, context: self::getContextException(403)), false],
            ['/404',   RecordFactory::create(Logger::ERROR, context: self::getContextException(404)), false],
            ['/405',   RecordFactory::create(Logger::ERROR, context: self::getContextException(405)), false],
            ['/500',   RecordFactory::create(Logger::ERROR, context: self::getContextException(500)), true],
        ];
    }

    private static function getContextException(int $code): array
    {
        return ['exception' => new HttpException($code)];
    }
}
$message = $trans($template$parameters, 'validators');
                        $violations->add(new ConstraintViolation($message$template$parameters, null, $error->getPath(), null));
                    }
                    $payload = $e->getData();
                }

                if (null !== $payload) {
                    $violations->addAll($this->validator->validate($payload, null, $argument->validationGroups ?? null));
                }

                if (\count($violations)) {
                    throw new HttpException($validationFailedCodeimplode("\n", array_map(static fn ($e) => $e->getMessage()iterator_to_array($violations)))new ValidationFailedException($payload$violations));
                }
            } else {
                try {
                    $payload = $this->$payloadMapper($request$type$argument);
                } catch (PartialDenormalizationException $e) {
                    throw new HttpException($validationFailedCodeimplode("\n", array_map(static fn ($e) => $e->getMessage()$e->getErrors()))$e);
                }
            }

            if (null === $payload) {
                $payload = match (true) {
                    
yield 'custom status code' => [
            new Request(),
            new NotFoundHttpException('Page not found.'),
            404,
            'The server returned a "404 Not Found".',
        ];

        $request = new Request();
        $request->attributes->set('_format', 'unknown');
        yield 'default HTML format for unknown formats' => [
            $request,
            new HttpException(405, 'Invalid request.'),
            405,
            'The server returned a "405 Method Not Allowed".',
        ];
    }

    public function testPreviewController()
    {
        $_controller = 'error_controller';
        $code = 404;

        $kernel = $this->createMock(HttpKernelInterface::class);
        

    protected function deliver(Response $response): ?string
    {
        if (!$response->isSuccessful()) {
            $responseStatusCode = $response->getStatusCode();
            throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %d).', $this->requestStack->getCurrentRequest()->getUri()$responseStatusCode), 0, new HttpException($responseStatusCode));
        }

        if (!$response instanceof StreamedResponse) {
            return $response->getContent();
        }

        $response->sendContent();

        return null;
    }
}
$message = $trans($template$parameters, 'validators');
                        $violations->add(new ConstraintViolation($message$template$parameters, null, $error->getPath(), null));
                    }
                    $payload = $e->getData();
                }

                if (null !== $payload) {
                    $violations->addAll($this->validator->validate($payload, null, $argument->validationGroups ?? null));
                }

                if (\count($violations)) {
                    throw new HttpException($validationFailedCodeimplode("\n", array_map(static fn ($e) => $e->getMessage()iterator_to_array($violations)))new ValidationFailedException($payload$violations));
                }
            } else {
                try {
                    $payload = $this->$payloadMapper($request$type$argument);
                } catch (PartialDenormalizationException $e) {
                    throw new HttpException($validationFailedCodeimplode("\n", array_map(static fn ($e) => $e->getMessage()$e->getErrors()))$e);
                }
            }

            if (null === $payload) {
                $payload = match (true) {
                    

  public function testOnExceptionResponseBuilderException() {
    $form = ['#type' => 'form', '#build_id' => 'the_build_id'];
    $expected_form = $form + [
      '#build_id_old' => 'the_build_id',
    ];
    $form_state = new FormState();
    $exception = new FormAjaxException($form$form_state);
    $request = new Request([]['form_build_id' => 'the_build_id']);
    $commands = [];

    $expected_exception = new HttpException(500, 'The specified #ajax callback is empty or not callable.');
    $this->formAjaxResponseBuilder->expects($this->once())
      ->method('buildResponse')
      ->with($request$expected_form$form_state$commands)
      ->willThrowException($expected_exception);

    $this->assertResponseFromException($request$exception, NULL);
    $this->assertSame($expected_exception$this->event->getThrowable());
  }

  /** * @covers ::onException */
return [];
        }

        if (null !== $token = $this->tokenStorage->getToken()) {
            return [$token];
        }

        if ($argument->isNullable()) {
            return [];
        }

        throw new HttpException(Response::HTTP_UNAUTHORIZED, 'A security token is required but the token storage is empty.');
    }
}

    public function redirectAction(Request $request, string $route, bool $permanent = false, bool|array $ignoreAttributes = false, bool $keepRequestMethod = false, bool $keepQueryParams = false): Response
    {
        if ('' == $route) {
            throw new HttpException($permanent ? 410 : 404);
        }

        $attributes = [];
        if (false === $ignoreAttributes || \is_array($ignoreAttributes)) {
            $attributes = $request->attributes->get('_route_params');

            if ($keepQueryParams) {
                if ($query = $request->server->get('QUERY_STRING')) {
                    $query = HeaderUtils::parseQuery($query);
                } else {
                    $query = $request->query->all();
                }
Home | Imprint | This part of the site doesn't use cookies.