public function onKernelException(GetResponseForExceptionEvent $event) { $this->logger->notice(sprintf('Exceptions catcher listener: catch kernel.exception event (exception: %s)', $event->getException()->getMessage())); // If this is not a master request, skip handling if (!$event->isMasterRequest()) { $this->logger->debug('Exceptions catcher listener: this is not master request, skip'); return; } // If content already prepared if ($event->hasResponse()) { $this->logger->debug('Exceptions catcher listener: event already has response, skip'); return; } // Getting action $apiServerAction = $event->getRequest()->attributes->get('apiAction'); /* @var $apiServerAction ApiServerAction */ // Something wrong if (!$apiServerAction) { $this->logger->error('Request parser listener: request has no apiAction attribute, sending empty response'); $event->setResponse(new JsonResponse([])); return; } // Getting api server interface $apiServerInterface = $apiServerAction->getApiServerInterface(); // Creating api response $apiResponse = $apiServerInterface->getExceptionResponse($event->getException()->getMessage()); // Setting response $event->setResponse(new JsonResponse($apiResponse->export())); }
/** * 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())); } }
public function onSilexError(GetResponseForExceptionEvent $event) { if (!$event->getException() instanceof \Bridge_Exception) { return; } $e = $event->getException(); $request = $event->getRequest(); $params = ['account' => null, 'elements' => [], 'message' => $e->getMessage(), 'error_message' => null, 'notice_message' => null, 'file' => $e->getFile(), 'line' => $e->getLine(), 'r_method' => $request->getMethod(), 'r_action' => $request->getRequestUri(), 'r_parameters' => $request->getMethod() == 'GET' ? [] : $request->request->all()]; if ($e instanceof \Bridge_Exception_ApiConnectorNotConfigured) { $params = array_replace($params, ['account' => $this->app['bridge.account']]); $response = new Response($this->app['twig']->render('/prod/actions/Bridge/notconfigured.html.twig', $params), 200, ['X-Status-Code' => 200]); } elseif ($e instanceof \Bridge_Exception_ApiConnectorNotConnected) { $params = array_replace($params, ['account' => $this->app['bridge.account']]); $response = new Response($this->app['twig']->render('/prod/actions/Bridge/disconnected.html.twig', $params), 200, ['X-Status-Code' => 200]); } elseif ($e instanceof \Bridge_Exception_ApiConnectorAccessTokenFailed) { $params = array_replace($params, ['account' => $this->app['bridge.account']]); $response = new Response($this->app['twig']->render('/prod/actions/Bridge/disconnected.html.twig', $params), 200, ['X-Status-Code' => 200]); } elseif ($e instanceof \Bridge_Exception_ApiDisabled) { $params = array_replace($params, ['api' => $e->get_api()]); $response = new Response($this->app['twig']->render('/prod/actions/Bridge/deactivated.html.twig', $params), 200, ['X-Status-Code' => 200]); } else { $response = new Response($this->app['twig']->render('/prod/actions/Bridge/error.html.twig', $params), 200, ['X-Status-Code' => 200]); } $response->headers->set('Phrasea-StatusCode', 200); $event->setResponse($response); }
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 handleKernelException(GetResponseForExceptionEvent $event) { if ($this->container->get('kernel')->getEnvironment() !== 'dev') { $exception = FlattenException::create($event->getException()); // First, log the exception to the standard error logs. $this->container->get('logger')->error(' In File ' . $exception->getFile() . ', on line ' . $exception->getLine() . ': ' . $exception->getMessage()); // Determine what the HTTP status code should be. if ($event->getException() instanceof \Symfony\Component\HttpKernel\Exception\HttpException) { $httpStatusCode = $event->getException()->getStatusCode(); } else { $httpStatusCode = $exception->getCode(); if ($exception->getCode() < 100 || $exception->getCode() >= 600) { $httpStatusCode = 500; } } $parameters = ['status_code' => $httpStatusCode, 'status_text' => $exception->getMessage(), 'exception' => $exception]; if (in_array('application/json', $event->getRequest()->getAcceptableContentTypes())) { $errorContent = $this->container->get('templating')->render(':default:exception.json.twig', $parameters); } else { $errorContent = $this->container->get('templating')->render(':default:error.html.twig', $parameters); } $response = new Response($errorContent, $httpStatusCode); $response->setProtocolVersion('1.1'); $event->setResponse($response); } }
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); }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { // Skip HTTP exception if ($event->getException() instanceof HttpException) { return; } $this->setException($event->getException()); }
/** * @test */ public function it_converts_numbers_to_http_status_code_exception() { $logger = \Phake::mock('Psr\\Log\\LoggerInterface'); $listener = new ConvertExceptionListener($logger, array('OutOfBoundsException' => 405)); $listener->onKernelException($event = new GetResponseForExceptionEvent(\Phake::mock('Symfony\\Component\\HttpKernel\\KernelInterface'), \Phake::mock('Symfony\\Component\\HttpFoundation\\Request'), 0, $original = new OutOfBoundsException())); $this->assertInstanceOf('Symfony\\Component\\HttpKernel\\Exception\\HttpException', $event->getException()); $this->assertEquals(405, $event->getException()->getStatusCode()); $this->assertSame($original, $event->getException()->getPrevious()); }
/** * onKernelException * * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof HttpExceptionInterface) { $code = $event->getException()->getStatusCode(); } else { $code = 'unknown'; } $this->eventDispatcher->dispatch('statsd.exception', new StatsdEvent($code)); }
public function onKernelException(GetResponseForExceptionEvent $event) { if ($this->kernel->getEnvironment() != 'dev') { $exception = $event->getException(); if (!$exception instanceof HttpException) { $this->logger->error($exception->getMessage()); } $event->setResponse(new RedirectResponse($this->router->generate('music_error', ['code' => $event->getException() instanceof HttpException ? $exception->getStatusCode() : 500]))); } }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { if (false == $event->getException() instanceof ReplyInterface) { return; } $response = $this->replyToSymfonyResponseConverter->convert($event->getException()); if (false == $response->headers->has('X-Status-Code')) { $response->headers->set('X-Status-Code', $response->getStatusCode()); } $event->setResponse($response); }
/** * Exception error handler * * @param GetResponseForExceptionEvent $event * * @return void */ public function onKernelException(GetResponseForExceptionEvent $event) { if ($this->isIgnored($event->getException())) { return; } if ($this->mailer) { $this->mailer->sendException($event->getRequest(), $event->getException()); } if ($this->statsd) { $this->statsd->increment("exception"); } }
/** * 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)); } } }
/** * {@inheritdoc} */ public function onSilexError(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $code = $exception->getCode(); if (is_numeric($code)) { $code = max(1, intval($code)); } else { $code = 1; } $this->app['console.status'] = $code; $this->app['console']->renderException($event->getException(), $this->app['console.output']); $event->setResponse(new Response()); }
public function onSilexError(GetResponseForExceptionEvent $event) { $handler = new DebugExceptionHandler($this->debug); if (method_exists($handler, 'getHtml')) { $exception = $event->getException(); if (!$exception instanceof FlattenException) { $exception = FlattenException::create($exception); } $response = Response::create($handler->getHtml($exception), $exception->getStatusCode(), $exception->getHeaders())->setCharset(ini_get('default_charset')); } else { // BC with Symfony < 2.8 $response = $handler->createResponse($event->getException()); } $event->setResponse($response); }
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)); } } }
/** * 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(); }
/** * 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) { $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); }
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) { $ex = $event->getException(); if ($ex instanceof BadRequestException) { $event->setResponse($this->renderer->render($event->getRequest(), $ex)); } }
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())); }
/** * 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) { $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) { 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); }
/** * 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); } }
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); }
/** * 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); } } }
/** * 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(); }
/** * 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) { } }