This exception will be thrown if no response is set in the event.
public setException ( Exception $exception ) | ||
$exception | Exception | The thrown exception |
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($this->env != "prod") { $event->setException($exception); return; } try { $code = 404; if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) { $code = 404; } else { if ($exception instanceof \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException) { $code = 403; } } $file = $code; if ($this->env != "prod") { //$file = $file . '.' . $this->env; } $file = $file . '.html.twig'; $template = $this->siteManager->getTemplate("portal"); $template = "SymbbTemplateDefaultBundle:Exception:" . $file; $response = new Response($this->templating->render($template, array('status_code' => $code, 'status_text' => $exception->getMessage(), 'exception' => $exception))); // setup the Response object based on the caught exception $event->setResponse($response); } catch (\Exception $exc) { $event->setException($exception); } // you can alternatively set a new Exception // $exception = new \Exception('Some special exception'); // $event->setException($exception); }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof NotFoundException) { $event->setException(new NotFoundHttpException($this->getTranslatedMessage($exception), $exception)); } elseif ($exception instanceof UnauthorizedException) { $event->setException(new AccessDeniedException($this->getTranslatedMessage($exception), $exception)); } elseif ($exception instanceof BadStateException || $exception instanceof InvalidArgumentException) { $event->setException(new BadRequestHttpException($this->getTranslatedMessage($exception), $exception)); } elseif ($exception instanceof Translatable) { $event->setException(new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, get_class($exception) . ': ' . $this->getTranslatedMessage($exception), $exception)); } }
/** * @param GetResponseForExceptionEvent $event * @return bool|void */ public function onKernelException(GetResponseForExceptionEvent $event) { static $handling; if (true === $handling) { return false; } $handling = true; $exception = $event->getException(); if ($exception instanceof AccessDeniedHttpException) { if (StringUtils::startsWith($exception->getMessage(), 'Expression "has_role(\'ROLE_')) { $message = 'Bu alana erişebilmek için kullanıcı girişi yapılmalıdır'; $statusCode = 401; } else { $message = $exception->getMessage(); $statusCode = $exception->getStatusCode(); } $exception = new HttpException($statusCode, $message, $exception); $event->setException($exception); parent::onKernelException($event); } elseif ($exception instanceof InsufficientAuthenticationException) { $exception = new AccessDeniedHttpException('Bu alana erişebilmek için geçerli bir kullanıcı kimliği belirtilmelidir', $exception); $event->setException($exception); parent::onKernelException($event); } $handling = false; return false; }
public function exceptionHandler(GetResponseForExceptionEvent $event) { if ($event->getException() instanceof PluginException) { return; } $event->setException(new PluginException(sprintf('The plugin `%s` from bundle `%s` [%s] errored.', $this->plugin['plugin'], $this->bundleName, $this->pluginDef->getController()), null, $event->getException())); }
public function onJsonRpcException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof InvalidRequestException) { $event->setException(new BadRequestHttpException($exception->getMessage(), $exception)); } }
/** * Catches failed parameter conversions and throw a 404 instead. * * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event */ public function onException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof ParamNotConvertedException) { $event->setException(new NotFoundHttpException($exception->getMessage(), $exception)); } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if (!$exception instanceof BlockadeException) { return; } //try to get a response from one of the resolvers. It //could be a redirect, an access denied page, or anything //really try { foreach ($this->resolvers as $resolver) { $driver = $exception->getDriver(); if (!$driver || !$resolver->supportsDriver($driver)) { continue; } if (!$resolver->supportsException($exception)) { continue; } $request = $event->getRequest(); $response = $resolver->onException($exception, $request); if ($response instanceof Response) { $event->setResponse($response); return; } } //no response has been created by now, so let other //exception listeners handle it return; } catch (\Exception $e) { //if anything at all goes wrong in calling the //resolvers, pass the exception on $event->setException($e); } }
public function onKernelException(GetResponseForExceptionEvent $event) { static $handling; if (true === $handling) { return false; } $request = $event->getRequest(); if (empty($this->formats[$request->getRequestFormat()]) && empty($this->formats[$request->getContentType()])) { return false; } $handling = true; $exception = $event->getException(); if ($exception instanceof AccessDeniedException) { $exception = new AccessDeniedHttpException('You do not have the necessary permissions', $exception); $event->setException($exception); parent::onKernelException($event); } elseif ($exception instanceof AuthenticationException) { if ($this->challenge) { $exception = new UnauthorizedHttpException($this->challenge, 'You are not authenticated', $exception); } else { $exception = new HttpException(401, 'You are not authenticated', $exception); } $event->setException($exception); parent::onKernelException($event); } $handling = false; }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if (!$exception instanceof ParamValidationFailedException) { return; } $event->setException($this->convertException($exception)); }
/** * Handles security related exceptions. * * @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance */ public function onCoreException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $request = $event->getRequest(); if ($exception instanceof AuthenticationException) { if (null !== $this->logger) { $this->logger->info(sprintf('Authentication exception occurred; redirecting to authentication entry point (%s)', $exception->getMessage())); } try { $response = $this->startAuthentication($request, $exception); } catch (\Exception $e) { $event->setException($e); return; } } elseif ($exception instanceof AccessDeniedException) { $token = $this->context->getToken(); if (!$this->authenticationTrustResolver->isFullFledged($token)) { if (null !== $this->logger) { $this->logger->info('Access denied (user is not fully authenticated); redirecting to authentication entry point'); } try { $response = $this->startAuthentication($request, new InsufficientAuthenticationException('Full authentication is required to access this resource.', $token, 0, $exception)); } catch (\Exception $e) { $event->setException($e); return; } } else { if (null !== $this->logger) { $this->logger->info('Access is denied (and user is neither anonymous, nor remember-me)'); } try { if (null !== $this->accessDeniedHandler) { $response = $this->accessDeniedHandler->handle($request, $exception); if (!$response instanceof Response) { return; } } else { if (null === $this->errorPage) { return; } $subRequest = Request::create($this->errorPage, 'get', array(), $request->cookies->all(), array(), $request->server->all()); $subRequest->attributes->set(SecurityContextInterface::ACCESS_DENIED_ERROR, $exception); $response = $event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true); $response->setStatusCode(403); } } catch (\Exception $e) { if (null !== $this->logger) { $this->logger->err(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage())); } $event->setException(new \RuntimeException('Exception thrown when handling an exception.', 0, $e)); return; } } } else { return; } $event->setResponse($response); }
/** * Maps known exceptions to HTTP exceptions. * * @param GetResponseForExceptionEvent $event The event object */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $class = $this->getTargetClass($exception); if (null === $class) { return; } if (null !== ($httpException = $this->convertToHttpException($exception, $class))) { $event->setException($httpException); } }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof HttpException) { return; } $exception = $this->decorateException($exception); if ($exception) { $event->setException($exception); } }
/** * Maps known exceptions to HTTP exceptions. * * @param GetResponseForExceptionEvent $event The event object */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $class = get_class($exception); if (!isset($this->mapper[$class])) { return; } if (null !== ($httpException = $this->convertToHttpException($exception, $this->mapper[$class]))) { $event->setException($httpException); } }
/** * If exception type is 404, display the Orchestra 404 node instead of Symfony exception * * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { if ($event->getException() instanceof DisplayBlockException) { $event->getRequest()->setRequestFormat('fragment.' . $event->getRequest()->getRequestFormat()); $event->setException($event->getException()->getPrevious()); } elseif ($event->getException() instanceof HttpExceptionInterface && '404' == $event->getException()->getStatusCode()) { $this->setCurrentSiteInfo(trim($this->request->getHost(), '/'), trim($this->request->getPathInfo(), '/')); if ($html = $this->getCustom404Html()) { $event->setResponse(new Response($html, 404)); } } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof HttpExceptionInterface) { return; } $convertedExceptionClass = $this->findConvertToExceptionClass($exception); if (!$convertedExceptionClass) { return; } $this->logException($exception); $convertedException = $this->convertException($exception, $convertedExceptionClass); $event->setException($convertedException); }
/** * Set the properly exception for event. */ public function onAccessDeniedException(GetResponseForExceptionEvent $event) { if ($event->getException() instanceof AccessDeniedHttpException) { $admin_only = \Drupal::config('m4032404.settings')->get('admin_only'); $route = \Drupal::routeMatch()->getRouteObject(); $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route); if ($admin_only && !$is_admin) { // @todo revisit this when r4032login is ready for 8.x. if (function_exists('r4032login_redirect')) { return r4032login_redirect(); } } else { $event->setException(new NotFoundHttpException()); } } }
public function onCKFinderError(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $exceptionCode = $exception->getCode() ?: Error::UNKNOWN; $replacements = array(); $httpStatusCode = 200; if ($exception instanceof CKFinderException) { $replacements = $exception->getParameters(); $httpStatusCode = $exception->getHttpStatusCode(); } $message = $exceptionCode === Error::CUSTOM_ERROR ? $exception->getMessage() : $this->translator->translateErrorMessage($exceptionCode, $replacements); $response = JsonResponse::create()->withError($exceptionCode, $message); $event->setException(new HttpException($httpStatusCode)); $event->setResponse($response); if ($this->debug && $this->logger) { $this->logger->error($exception); } if (filter_var(ini_get('display_errors'), FILTER_VALIDATE_BOOLEAN)) { throw $exception; } }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { if (false == $event->getException() instanceof InteractiveRequestInterface) { return; } $interactiveRequest = $event->getException(); if ($interactiveRequest instanceof SymfonyResponseInteractiveRequest) { $event->setResponse($interactiveRequest->getResponse()); } elseif ($interactiveRequest instanceof ResponseInteractiveRequest) { $event->setResponse(new Response($interactiveRequest->getContent())); } elseif ($interactiveRequest instanceof RedirectUrlInteractiveRequest) { $event->setResponse(new RedirectResponse($interactiveRequest->getUrl())); } if ($event->getResponse()) { if (false == $event->getResponse()->headers->has('X-Status-Code')) { $event->getResponse()->headers->set('X-Status-Code', $event->getResponse()->getStatusCode()); } return; } $ro = new \ReflectionObject($interactiveRequest); $event->setException(new LogicException(sprintf('Cannot convert interactive request %s to symfony response.', $ro->getShortName()), null, $interactiveRequest)); }
/** * Respond with a challenge on access denied exceptions if appropriate. * * On a 403 (access denied), if there are no credentials on the request, some * authentication methods (e.g. basic auth) require that a challenge is sent * to the client. * * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event * The exception event. */ public function onExceptionSendChallenge(GetResponseForExceptionEvent $event) { if (isset($this->challengeProvider) && $event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) { $request = $event->getRequest(); $exception = $event->getException(); if ($exception instanceof AccessDeniedHttpException && !$this->authenticationProvider->applies($request) && (!isset($this->filter) || $this->filter->appliesToRoutedRequest($request, FALSE))) { $challenge_exception = $this->challengeProvider->challengeException($request, $exception); if ($challenge_exception) { $event->setException($challenge_exception); } } } }
/** * Catches a form AJAX exception and build a response from it. * * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event * The event to process. */ public function onException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $request = $event->getRequest(); // Render a nice error message in case we have a file upload which exceeds // the configured upload limit. if ($exception instanceof BrokenPostRequestException && $request->query->has(FormBuilderInterface::AJAX_FORM_REQUEST)) { $this->drupalSetMessage($this->t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', ['@size' => $this->formatSize($exception->getSize())]), 'error'); $response = new AjaxResponse(); $status_messages = ['#type' => 'status_messages']; $response->addCommand(new ReplaceCommand(NULL, $status_messages)); $response->headers->set('X-Status-Code', 200); $event->setResponse($response); return; } // Extract the form AJAX exception (it may have been passed to another // exception before reaching here). if ($exception = $this->getFormAjaxException($exception)) { $request = $event->getRequest(); $form = $exception->getForm(); $form_state = $exception->getFormState(); // Set the build ID from the request as the old build ID on the form. $form['#build_id_old'] = $request->get('form_build_id'); try { $response = $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, []); // Since this response is being set in place of an exception, explicitly // mark this as a 200 status. $response->headers->set('X-Status-Code', 200); $event->setResponse($response); } catch (\Exception $e) { // Otherwise, replace the existing exception with the new one. $event->setException($e); } } }
private function handleAccessDeniedException(GetResponseForExceptionEvent $event, AccessDeniedException $exception) { $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception)); $token = $this->context->getToken(); if (!$this->authenticationTrustResolver->isFullFledged($token)) { if (null !== $this->logger) { $this->logger->debug(sprintf('Access is denied (user is not fully authenticated) by "%s" at line %s; redirecting to authentication entry point', $exception->getFile(), $exception->getLine())); } try { $insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.', 0, $exception); $insufficientAuthenticationException->setToken($token); $event->setResponse($this->startAuthentication($event->getRequest(), $insufficientAuthenticationException)); } catch (\Exception $e) { $event->setException($e); } return; } if (null !== $this->logger) { $this->logger->debug(sprintf('Access is denied (and user is neither anonymous, nor remember-me) by "%s" at line %s', $exception->getFile(), $exception->getLine())); } try { if (null !== $this->accessDeniedHandler) { $response = $this->accessDeniedHandler->handle($event->getRequest(), $exception); if ($response instanceof Response) { $event->setResponse($response); } } elseif (null !== $this->errorPage) { $subRequest = $this->httpUtils->createRequest($event->getRequest(), $this->errorPage); $subRequest->attributes->set(Security::ACCESS_DENIED_ERROR, $exception); $event->setResponse($event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true)); } } catch (\Exception $e) { if (null !== $this->logger) { $this->logger->error(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage())); } $event->setException(new \RuntimeException('Exception thrown when handling an exception.', 0, $e)); } }
/** * {@inheritdoc} */ public function handleException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($GLOBALS['user']->isAnonymous() && $exception instanceof AccessDeniedHttpException) { if (!$this->applies($event->getRequest())) { $site_name = $this->configFactory->get('system.site')->get('name'); global $base_url; $challenge = String::format('Basic realm="@realm"', array('@realm' => !empty($site_name) ? $site_name : $base_url)); $event->setException(new UnauthorizedHttpException($challenge, 'No authentication credentials provided.', $exception)); } return TRUE; } return FALSE; }
/** * Handles a native error. * * @param GetResponseForExceptionEvent $event * * @throws mixed */ private function handleNativeError(GetResponseForExceptionEvent $event) { if (true === $this->debug) { return; } if (true === $this->status) { return; } $this->status = true; $exception = $event->getException(); $statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500; $cmsManager = $this->cmsManagerSelector->retrieve(); if ($event->getRequest()->get('_route') && !$this->decoratorStrategy->isRouteNameDecorable($event->getRequest()->get('_route'))) { return; } if (!$this->decoratorStrategy->isRouteUriDecorable($event->getRequest()->getPathInfo())) { return; } if (!$this->hasErrorCode($statusCode)) { return; } $message = sprintf('%s: %s (uncaught exception) at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()); $this->logException($exception, $exception, $message); try { $page = $this->getErrorCodePage($statusCode); $cmsManager->setCurrentPage($page); if ($page->getSite()->getLocale() !== $event->getRequest()->getLocale()) { // Compare locales because Request returns the default one if null. // If 404, LocaleListener from HttpKernel component of Symfony is not called. // It uses the "_locale" attribute set by SiteSelectorInterface to set the request locale. // So in order to translate messages, force here the locale with the site. $event->getRequest()->setLocale($page->getSite()->getLocale()); } $response = $this->pageServiceManager->execute($page, $event->getRequest(), array(), new Response('', $statusCode)); } catch (\Exception $e) { $this->logException($exception, $e); $event->setException($e); $this->handleInternalError($event); return; } $event->setResponse($response); }
/** * Register the event handler * * @param GetResponseForExceptionEvent $event * * @api */ public function onKernelException(GetResponseForExceptionEvent $event) { if (!in_array(get_class($event->getException()), $this->checkExceptions)) { return; } $exceptionMessage = $event->getException()->getMessage(); $prefixLength = mb_strlen($this->errorPrefix); // PDO Exception likes to place SQLState before the message // And do some other stuff... // HT000 is used for MySQL, but there is no support for 'custom errors' yet if ($event->getException() instanceof \PDOException) { if (!in_array($event->getException()->getCode(), array('P0001'))) { return; } // PostgreSQL if ('P0001' === $event->getException()->getCode() && preg_match('#^SQLSTATE\\[P0001\\]: Raise exception: \\d+ ERROR: (.+)#', $exceptionMessage, $messageMatch)) { $exceptionMessage = $messageMatch[1]; } else { return; } // @codeCoverageIgnoreEnd } if (mb_substr($exceptionMessage, 0, $prefixLength) === $this->errorPrefix) { $exceptionMessage = mb_substr($exceptionMessage, $prefixLength); $messageMatch = $this->parseMessage($exceptionMessage); $event->setException(new \Exception($this->translator->trans($messageMatch['message'], $messageMatch['params']), 0, $event->getException())); } }
/** * Handles security related exceptions. * * @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance */ public function onKernelException(GetResponseForExceptionEvent $event) { // we need to remove ourselves as the exception listener can be // different depending on the Request $event->getDispatcher()->removeListener(KernelEvents::EXCEPTION, array($this, 'onKernelException')); $exception = $event->getException(); $request = $event->getRequest(); // determine the actual cause for the exception while (null !== ($previous = $exception->getPrevious())) { $exception = $previous; } if ($exception instanceof AuthenticationException) { if (null !== $this->logger) { $this->logger->info(sprintf('Authentication exception occurred; redirecting to authentication entry point (%s)', $exception->getMessage())); } try { $response = $this->startAuthentication($request, $exception); } catch (\Exception $e) { $event->setException($e); return; } } elseif ($exception instanceof AccessDeniedException) { $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception)); $token = $this->context->getToken(); if (!$this->authenticationTrustResolver->isFullFledged($token)) { if (null !== $this->logger) { $this->logger->debug(sprintf('Access is denied (user is not fully authenticated) by "%s" at line %s; redirecting to authentication entry point', $exception->getFile(), $exception->getLine())); } try { $insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.', 0, $exception); $insufficientAuthenticationException->setToken($token); $response = $this->startAuthentication($request, $insufficientAuthenticationException); } catch (\Exception $e) { $event->setException($e); return; } } else { if (null !== $this->logger) { $this->logger->debug(sprintf('Access is denied (and user is neither anonymous, nor remember-me) by "%s" at line %s', $exception->getFile(), $exception->getLine())); } try { if (null !== $this->accessDeniedHandler) { $response = $this->accessDeniedHandler->handle($request, $exception); if (!$response instanceof Response) { return; } } elseif (null !== $this->errorPage) { $subRequest = $this->httpUtils->createRequest($request, $this->errorPage); $subRequest->attributes->set(SecurityContextInterface::ACCESS_DENIED_ERROR, $exception); $response = $event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true); } else { return; } } catch (\Exception $e) { if (null !== $this->logger) { $this->logger->error(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage())); } $event->setException(new \RuntimeException('Exception thrown when handling an exception.', 0, $e)); return; } } } elseif ($exception instanceof LogoutException) { if (null !== $this->logger) { $this->logger->info(sprintf('Logout exception occurred; wrapping with AccessDeniedHttpException (%s)', $exception->getMessage())); } return; } else { return; } $event->setResponse($response); }
/** * @param GetResponseForExceptionEvent $event */ public function onException(GetResponseForExceptionEvent $event) { if ($event->getException() instanceof NotValidCurrentPageException) { $event->setException(new NotFoundHttpException('Page Not Found', $event->getException())); } }
/** * {@inheritdoc} */ public function handleException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof AccessDeniedHttpException) { $event->setException(new UnauthorizedHttpException('Invalid consumer origin.', $exception)); return TRUE; } return FALSE; }
/** * Handles a native error * * @param GetResponseForExceptionEvent $event * * @throws mixed */ private function handleNativeError(GetResponseForExceptionEvent $event) { if (true === $this->debug) { return; } if (true === $this->status) { return; } $this->status = true; $exception = $event->getException(); $statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500; $cmsManager = $this->cmsManagerSelector->retrieve(); if ($event->getRequest()->get('_route') && !$this->decoratorStrategy->isRouteNameDecorable($event->getRequest()->get('_route'))) { return; } if (!$this->decoratorStrategy->isRouteUriDecorable($event->getRequest()->getPathInfo())) { return; } if (!$this->hasErrorCode($statusCode)) { return; } $message = sprintf('%s: %s (uncaught exception) at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()); $this->logException($exception, $exception, $message); try { $page = $this->getErrorCodePage($statusCode); $cmsManager->setCurrentPage($page); $response = $this->pageServiceManager->execute($page, $event->getRequest(), array(), new Response('', $statusCode)); } catch (\Exception $e) { $this->logException($exception, $e); $event->setException($e); $this->handleInternalError($event); return; } $event->setResponse($response); }