Call setResponse() to set the response that will be returned for the
current request. The propagation of this event is stopped as soon as a
response is set.
You can also call setException() to replace the thrown exception. This
exception will be thrown if no response is set during processing of this
event.
public function onKernelException(GetResponseForExceptionEvent $event) { // only reply to /api URLs if (strpos($event->getRequest()->getPathInfo(), '/api') !== 0) { return; } $e = $event->getException(); $statusCode = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500; // allow 500 errors to be thrown if ($this->debug && $statusCode >= 500) { return; } if ($e instanceof ApiProblemException) { $apiProblem = $e->getApiProblem(); } else { $apiProblem = new ApiProblem($statusCode); /* * If it's an HttpException message (e.g. for 404, 403), * we'll say as a rule that the exception message is safe * for the client. Otherwise, it could be some sensitive * low-level exception, which should *not* be exposed */ if ($e instanceof HttpExceptionInterface) { $apiProblem->set('detail', $e->getMessage()); } } $response = $this->responseFactory->createResponse($apiProblem); $event->setResponse($response); }
/** * Handles the onKernelException event. * * @param GetResponseForExceptionEvent $event A GetResponseForExceptionEvent instance */ public function onKernelException(GetResponseForExceptionEvent $event) { if ($this->onlyMasterRequests && !$event->isMasterRequest()) { return; } $this->exception = $event->getException(); }
/** * 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); } } }
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); } }
/** * Replaces the response in case an EnforcedResponseException was thrown. */ public function onKernelException(GetResponseForExceptionEvent $event) { if ($response = EnforcedResponse::createFromException($event->getException())) { // Setting the response stops the event propagation. $event->setResponse($response); } }
public function onKernelException(GetResponseForExceptionEvent $event) { $e = $event->getException(); $statusCode = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500; // allow 500 errors to be thrown if ($this->debug && $statusCode >= 500) { return; } if ($e instanceof ApiProblemException) { $apiProblem = $e->getApiProblem(); } else { $apiProblem = new ApiProblem($statusCode); /* * If it's an HttpException message (e.g. for 404, 403), * we'll say as a rule that the exception message is safe * for the client. Otherwise, it could be some sensitive * low-level exception, which should *not* be exposed */ if ($e instanceof HttpExceptionInterface) { $apiProblem->set('detail', $e->getMessage()); } } $data = $apiProblem->toArray(); $response = new JsonResponse($data, $apiProblem->getStatusCode()); $response->headers->set('Content-Type', 'application/json'); $event->setResponse($response); }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $flattenException = FlattenException::create($exception); $msg = 'Something went wrong! (' . $flattenException->getMessage() . ')'; $event->setResponse(new Response($msg, $flattenException->getStatusCode())); }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $whoops = $this->handler->handle($event->getRequest(), $exception->getCode()); $whoopsResponse = $whoops->handleException($exception); $event->setResponse(new Response($whoopsResponse)); }
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())); }
/** * @param GetResponseForExceptionEvent $event */ public function onException(GetResponseForExceptionEvent $event) { if (!$event->isMasterRequest()) { return; } $this->eventDispatcher->dispatch(Events::REQUEST_ENDS, new RequestEnded($event->getRequest(), $event->getResponse(), $event->getException())); }
/** * @param GetResponseForExceptionEvent $event * * @return RedirectResponse|null * * @throws \LogicException If the current page is inside the page range */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if (!$exception instanceof OutOfBoundsException) { return; } $pageNumber = $exception->getPageNumber(); $pageCount = $exception->getPageCount(); if ($pageCount < 1) { return; // No pages...so let the exception fall through. } $queryBag = clone $event->getRequest()->query; if ($pageNumber > $pageCount) { $queryBag->set($exception->getRedirectKey(), $pageCount); } elseif ($pageNumber < 1) { $queryBag->set($exception->getRedirectKey(), 1); } else { return; // Super weird, because current page is within the bounds, fall through. } if (null !== ($qs = http_build_query($queryBag->all(), '', '&'))) { $qs = '?' . $qs; } // Create identical uri except for the page key in the query string which // was changed by this listener. // // @see Symfony\Component\HttpFoundation\Request::getUri() $request = $event->getRequest(); $uri = $request->getSchemeAndHttpHost() . $request->getBaseUrl() . $request->getPathInfo() . $qs; $event->setResponse(new RedirectResponse($uri)); }
public function onKernelException(GetResponseForExceptionEvent $event) { static $handling; if (true === $handling) { return false; } $handling = true; $exception = $event->getException(); $request = $event->getRequest(); $this->logException($exception, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine())); $attributes = array('_controller' => $this->controller, 'exception' => FlattenException::create($exception), 'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null, 'format' => $request->getRequestFormat()); $request = $request->duplicate(null, null, $attributes); $request->setMethod('GET'); try { $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, true); } catch (\Exception $e) { $this->logException($exception, sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage()), false); // set handling to false otherwise it wont be able to handle further more $handling = false; // re-throw the exception from within HttpKernel as this is a catch-all return; } $event->setResponse($response); $handling = false; }
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) { if ($event->getException() instanceof NotFoundHttpException) { $response = new RedirectResponse('karkeu'); $event->setResponse($response); } }
/** * Event handler that renders custom pages in case of a NotFoundHttpException (404) * or a AccessDeniedHttpException (403). * * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { if ('dev' == $this->kernel->getEnvironment()) { return; } $exception = $event->getException(); $this->request->setLocale($this->defaultLocale); $this->request->setDefaultLocale($this->defaultLocale); if ($exception instanceof NotFoundHttpException) { $section = $this->getExceptionSection(404, '404 Error'); $this->core->addNavigationElement($section); $unifikRequest = $this->generateUnifikRequest($section); $this->setUnifikRequestAttributes($unifikRequest); $this->request->setLocale($this->request->attributes->get('_locale', $this->defaultLocale)); $this->request->setDefaultLocale($this->request->attributes->get('_locale', $this->defaultLocale)); $this->entityManager->getRepository('UnifikSystemBundle:Section')->setLocale($this->request->attributes->get('_locale')); $response = $this->templating->renderResponse('UnifikSystemBundle:Frontend/Exception:404.html.twig', array('section' => $section)); $response->setStatusCode(404); $event->setResponse($response); } elseif ($exception instanceof AccessDeniedHttpException) { $section = $this->getExceptionSection(403, '403 Error'); $this->core->addNavigationElement($section); $unifikRequest = $this->generateUnifikRequest($section); $this->setUnifikRequestAttributes($unifikRequest); $response = $this->templating->renderResponse('UnifikSystemBundle:Frontend/Exception:403.html.twig', array('section' => $section)); $response->setStatusCode(403); $event->setResponse($response); } }
/** * This listener is run when the KernelEvents::EXCEPTION event is triggered * * @param GetResponseForExceptionEvent $event * @return null */ public function on_kernel_exception(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $message = $exception->getMessage(); if ($exception instanceof \phpbb\exception\exception_interface) { $message = $this->language->lang_array($message, $exception->get_parameters()); } if (!$event->getRequest()->isXmlHttpRequest()) { page_header($this->language->lang('INFORMATION')); $this->template->assign_vars(array('MESSAGE_TITLE' => $this->language->lang('INFORMATION'), 'MESSAGE_TEXT' => $message)); $this->template->set_filenames(array('body' => 'message_body.html')); page_footer(true, false, false); $response = new Response($this->template->assign_display('body'), 500); } else { $data = array(); if (!empty($message)) { $data['message'] = $message; } if (defined('DEBUG')) { $data['trace'] = $exception->getTrace(); } $response = new JsonResponse($data, 500); } if ($exception instanceof HttpExceptionInterface) { $response->setStatusCode($exception->getStatusCode()); $response->headers->add($exception->getHeaders()); } $event->setResponse($response); }
public function onKernelException(GetResponseForExceptionEvent $event) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { return; } $request = $event->getRequest(); if (!in_array($request->getRequestFormat(), array('soap', 'xml'))) { return; } elseif ('xml' === $request->getRequestFormat() && '_webservice_call' !== $request->attributes->get('_route')) { return; } $attributes = $request->attributes; if (!($webservice = $attributes->get('webservice'))) { return; } if (!$this->container->has(sprintf('besimple.soap.context.%s', $webservice))) { return; } // hack to retrieve the current WebService name in the controller $request->query->set('_besimple_soap_webservice', $webservice); $exception = $event->getException(); if ($exception instanceof \SoapFault) { $request->query->set('_besimple_soap_fault', $exception); } parent::onKernelException($event); }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $response = new JsonResponse(['errorMessage' => $event->getException()->getMessage(), 'stackTrace' => $event->getException()->getTraceAsString()]); if ($exception instanceof HttpExceptionInterface) { $response->setStatusCode($exception->getStatusCode()); } else { if ($exception instanceof AuthenticationException) { $response->setData(['errorMessage' => 'You don\'t have permissions to do this.']); $response->setStatusCode(Response::HTTP_FORBIDDEN); } else { if ($exception instanceof InvalidFormException) { $errors = []; foreach ($exception->getForm()->getErrors(true) as $error) { if ($error->getOrigin()) { $errors[$error->getOrigin()->getName()][] = $error->getMessage(); } } $data = ['errors' => $errors, 'errorMessage' => '']; $response->setData($data); $response->setStatusCode(Response::HTTP_BAD_REQUEST); } else { $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); } } } $event->setResponse($response); }
/** * 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)); } }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $code = $exception->getCode(); $debug = array('class' => get_class($exception), 'code' => $code, 'message' => $exception->getMessage()); $this->logger->error(print_r($debug, true)); // HttpExceptionInterface est un type d'exception spécial qui // contient le code statut et les détails de l'entête if ($exception instanceof NotFoundHttpException) { $data = array('error' => array('code' => $code ? $code : -3, 'message' => $exception->getMessage())); $response = new JsonResponse($data); $response->setStatusCode($exception->getStatusCode()); $response->headers->replace($exception->getHeaders()); $response->headers->set('Content-Type', 'application/json'); } elseif ($exception instanceof HttpExceptionInterface) { $data = array('error' => array('code' => $code ? $code : -2, 'message' => $exception->getMessage())); $response = new JsonResponse($data); $response->setStatusCode($exception->getStatusCode()); $response->headers->replace($exception->getHeaders()); $response->headers->set('Content-Type', 'application/json'); } else { $data = array('error' => array('code' => $code ? $code : -1, 'message' => 'Internal Server Error / ' . $exception->getMessage())); $response = new JsonResponse($data); $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); } // envoie notre objet réponse modifié à l'évènement $event->setResponse($response); }
public function onKernelException(GetResponseForExceptionEvent $event) { $ex = $event->getException(); if ($ex instanceof BadRequestException) { $event->setResponse($this->renderer->render($event->getRequest(), $ex)); } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $request = $event->getRequest(); $this->logException($exception, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine())); $attributes = array('_controller' => $this->controller, 'exception' => FlattenException::create($exception), 'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null, 'format' => $request->getRequestFormat()); $request = $request->duplicate(null, null, $attributes); $request->setMethod('GET'); try { $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false); } catch (\Exception $e) { $this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), false); $wrapper = $e; while ($prev = $wrapper->getPrevious()) { if ($exception === ($wrapper = $prev)) { throw $e; } } $prev = new \ReflectionProperty('Exception', 'previous'); $prev->setAccessible(true); $prev->setValue($wrapper, $exception); throw $e; } $event->setResponse($response); }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $response = new ExceptionResponse(500, $exception->getMessage()); if ($exception->getCode() >= 100 && $exception->getCode() < 600) { $response->setCode($exception->getCode()); } if ($exception instanceof HttpExceptionInterface) { $response->setCode($exception->getStatusCode()); } if ($exception instanceof IErrorException) { $response->setErrors($exception->getErrors()); } if ($this->container->get('kernel')->getEnvironment() == "dev") { $response->setStackTrace($exception->getTraceAsString()); } $json = $this->serializer->serialize($response, "json"); $jsonResponse = new Response($json, $response->getCode()); // HttpExceptionInterface is a special type of exception that // holds status code and header details if ($exception instanceof HttpExceptionInterface) { //$jsonResponse->setStatusCode($exception->getStatusCode()); $jsonResponse->headers->replace($exception->getHeaders()); } // Send the modified response object to the event $event->setResponse($jsonResponse); }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if (!$exception instanceof HttpExceptionInterface) { $this->interactor->noticeException($exception); } }
public function onKernelException(GetResponseForExceptionEvent $event) { $request = $event->getRequest(); /** @var Jsend $configuration */ $configuration = $request->attributes->get('_jsend'); if (!$configuration) { return; } $format = $request->getRequestFormat(); if (!$format || $format === "html") { return; } $error = $event->getException(); if (!$error instanceof HttpException) { return; } $result = array('status' => Jsend::STATUS_ERROR, 'message' => $error->getMessage(), 'code' => $error->getStatusCode()); if ($this->container->getParameter('kernel.environment') == 'dev' && $error->getTrace()) { $result['trace'] = $error->getTrace(); } $strategy = new ExceptionExclusionStrategy(); $context = SerializationContext::create(); $context->addExclusionStrategy($strategy); $content = $this->serializer->serialize($result, $format, $context); $response = new Response($content); if ($format == 'json') { $response->headers->set('Content-Type', 'application/json'); } $event->setResponse($response); }
/** * Log de l'erreur dans MongoDB */ public function onKernelException(GetResponseForExceptionEvent $event) { // don't do anything if it's not the master request if (!$event->isMasterRequest()) { return; } // Create logs try { $log = new ErrorLog(); $exception = $event->getException(); $request = $event->getRequest(); // Current User if ($this->securityContext->getToken() && $this->securityContext->isGranted('ROLE_USER')) { $log->setUsername($this->securityContext->getToken()->getUser()->getUsername()); $log->setUserid($this->securityContext->getToken()->getUser()->getId()); } else { $log->setUsername(null); } // Get error code if (method_exists($exception, 'getStatusCode')) { $log->setCode($exception->getStatusCode()); } else { $log->setCode($exception->getCode()); } $log->setMessage($exception->getMessage()); $log->setUrl($request->getUri()); $log->setIp($request->getClientIp()); $log->setReferer($request->headers->get('referer')); if (in_array($log->getCode(), array('0', '404', '500'))) { $this->em->persist($log); $this->em->flush(); } } catch (\Exception $e) { } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof AlreadyLinkedAccount) { $this->session->getFlashBag()->add('error', $this->translator->trans($exception->getMessage())); $url = $this->router->generate('fos_user_profile_edit'); $event->setResponse(new RedirectResponse($url)); } elseif ($exception instanceof MissingEmailException) { $url = $this->router->generate('lc_before_register_twitter'); $event->setResponse(new RedirectResponse($url)); } elseif ($exception instanceof LcEmailException) { $this->session->getFlashBag()->add('error', $this->translator->trans($exception->getMessage())); $url = $this->router->generate('lc_home'); $event->setResponse(new RedirectResponse($url)); } elseif ($exception instanceof \FacebookApiException) { $this->session->getFlashBag()->add('error', $this->translator->trans($exception->getMessage())); $url = $this->router->generate('lc_home'); $event->setResponse(new RedirectResponse($url)); } elseif ($exception instanceof LcFcGbException) { $url = $this->router->generate('lc_link_facebook'); $event->setResponse(new RedirectResponse($url)); } elseif ($exception instanceof LcValidationException) { $this->session->getFlashBag()->add('error', $this->translator->trans($exception->getMessage())); $url = $this->router->generate('fos_user_profile_edit'); $event->setResponse(new RedirectResponse($url)); } elseif ($exception instanceof NotFoundHttpException) { $request = $event->getRequest(); $route = $request->get('_route'); if ($route == 'fos_user_registration_confirm') { $this->session->getFlashBag()->add('error', $this->translator->trans('This e-mail is already confirmed.')); $url = $this->router->generate('fos_user_profile_edit'); $event->setResponse(new RedirectResponse($url)); } } }
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); }
/** * Handles the onCoreException event. * * @param GetResponseForExceptionEvent $event A GetResponseForExceptionEvent instance */ public function onCoreException(GetResponseForExceptionEvent $event) { if ($this->onlyMasterRequests && HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { return; } $this->exception = $event->getException(); }
public function onKernelException(GetResponseForExceptionEvent $event) { if ($event->getException() instanceof AccessDeniedException) { $event->setResponse(new JsonResponse(['error' => 'access_denied'])); $event->stopPropagation(); } }