/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $logRef = uniqid(); $exception = $event->getException(); if ($exception instanceof NotFoundHttpException) { $event->setResponse(new VndErrorResponse("Not found", Response::HTTP_NOT_FOUND)); return; } if ($exception instanceof AuthenticationException) { $event->setResponse(new VndErrorResponse("Unauthorized", Response::HTTP_UNAUTHORIZED)); return; } new VndErrorResponse("Authentication Failure", Response::HTTP_UNAUTHORIZED); $code = $exception->getCode(); if (strlen($code) !== 3) { $this->fallback($message, $code, $logRef, $exception); } else { switch (substr($code, 0, 1)) { case '4': $message = 'Input Error'; $this->logger->notice("Input error [logref {$logRef}]: " . $exception->__toString()); break; case '5': $message = 'Server Error'; $this->logger->error("Runtime error [logref {$logRef}]: " . $exception->__toString()); break; default: $this->fallback($message, $code, $logRef, $exception); } } $event->setResponse(new VndErrorResponse($message, $code, $logRef)); }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $response = new JsonResponse(); $detail = sprintf("Message: %s\nFile: %s:%s", $exception->getMessage(), $exception->getFile(), $exception->getLine()); $data = ['type' => '#0', 'code' => 0, 'title' => 'Internal Server Error', 'status' => JsonResponse::HTTP_INTERNAL_SERVER_ERROR, 'detail' => $detail]; $response->setStatusCode(JsonResponse::HTTP_INTERNAL_SERVER_ERROR); $response->setData($data); if ($exception instanceof HttpExceptionInterface) { $response->headers->replace($exception->getHeaders()); } if ($exception instanceof HttpException) { $data = ['type' => '#' . $exception->getCode(), 'code' => $exception->getCode(), 'title' => $exception->getMessage(), 'status' => JsonResponse::HTTP_BAD_REQUEST, 'detail' => $exception->getDetails()]; $response->setStatusCode(JsonResponse::HTTP_BAD_REQUEST); $response->setData($data); } if ($exception instanceof AccessDeniedHttpException) { $event->setResponse(new Response("", 403)); } else { $event->setResponse($response); } if (!in_array($this->kernel->getEnvironment(), array('dev', 'test'))) { unset($data['detail']); } }
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())); }
/** * 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); } }
protected function ensureResponse($response, GetResponseForExceptionEvent $event) { if ($response instanceof Response) { $event->setResponse($response); } else { $viewEvent = new GetResponseForControllerResultEvent($this->app['kernel'], $event->getRequest(), $event->getRequestType(), $response); $this->app['dispatcher']->dispatch(KernelEvents::VIEW, $viewEvent); if ($viewEvent->hasResponse()) { $event->setResponse($viewEvent->getResponse()); } } }
public function onSilexError(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof BadResponseException && false !== strpos($exception->getMessage(), '[status code] 401')) { $event->setResponse(new Response('Unauthorized', Response::HTTP_UNAUTHORIZED)); return; } if ($exception instanceof BadResponseException && false !== strpos($exception->getMessage(), '[status code] 403')) { $event->setResponse(new Response('Forbidden', Response::HTTP_FORBIDDEN)); return; } }
public function checkRedirectException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof ExceptionRedirectException) { $response = RedirectResponse::create($exception->getUrl(), $exception->getStatusCode()); $event->setResponse($response); } elseif ($exception instanceof AuthenticationException) { // Redirect to the login template $response = RedirectResponse::create($this->urlManager->viewUrl($exception->getLoginTemplate())); $event->setResponse($response); } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof NotFoundHttpException) { // we don't need to explicitly set 404 status, HttpKernel will do this for us. if ($this->app['errorPage.notFound'] && ($page = \PageQuery::create()->findPk($this->app['errorPage.notFound']))) { $generator = AbstractGenerator::create($this->app, $page->getActivePageRevision()); $event->setResponse($generator->render()); } else { $event->setResponse(new Response('Page not found')); } } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof ValidationException) { $event->setResponse($this->templating->renderResponse('ICupPublicSiteBundle:Errors:' . strtolower($exception->getMessage()) . '.html.twig', array('redirect' => $this->router->generate('_icup')))); $this->logger->addError("ValidationException " . $exception->getMessage() . ": " . $exception->getDebugInfo() . ' - ' . $exception->getFile() . ':' . $exception->getLine()); } elseif ($exception instanceof RedirectException) { $this->logger->addDebug("Handling RedirectException"); $response = $exception->getResponse(); $response->setStatusCode(200); $event->setResponse($response); } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof PayloadValidationException) { $response = new JsonResponse($exception->getErrors(), JsonResponse::HTTP_BAD_REQUEST); $event->setResponse($response); return; } else { if ($exception instanceof HttpException) { $response = new JsonResponse(['message' => $exception->getMessage()], $exception->getStatusCode()); $event->setResponse($response); return; } } }
public function onKernelException(GetResponseForExceptionEvent $event) { if ($event->getException() instanceof NotFoundHttpException) { $response = new RedirectResponse('karkeu'); $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); }
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 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) { $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); }
/** * 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 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 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 authenticationException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof AuthenticationException) { $event->setResponse(RedirectResponse::create($exception->getLoginTemplate())); } }
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) { // 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); }
public function onKernelException(GetResponseForExceptionEvent $event) { if ($event->getException() instanceof AccessDeniedException) { $event->setResponse(new JsonResponse(['error' => 'access_denied'])); $event->stopPropagation(); } }
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) { 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) { $ex = $event->getException(); if ($ex instanceof BadRequestException) { $event->setResponse($this->renderer->render($event->getRequest(), $ex)); } }
/** * @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) { $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(); $whoops = $this->handler->handle($event->getRequest(), $exception->getCode()); $whoopsResponse = $whoops->handleException($exception); $event->setResponse(new Response($whoopsResponse)); }
/** * 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); } } }
/** * 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); }