Handle uncaught exceptions in application.

@param  Exception $e
@param  Request   $request
@param  string    $type

@return Response

@throws \Exception
514107
protected function handleException(\Exception $e, $request, $type)
    {
        $event = new FilterExceptionEvent($this, $request, $type);
        $event->setException($e);

        $this->getDispatcher()->dispatch(KernelEvents::EXCEPTION, $event);

        $e = $event->getException();

        if ( ! $event->hasResponse()) {
            throw $e;
        }

        $response = $event->getResponse();

        if ( ! $response->isClientError() && ! $response->isServerError() && ! $response->isRedirect()) {
            if ($e instanceof HttpExceptionInterface) {
                $response->setStatusCode($e->getStatusCode());
                $response->headers->add($e->getHeaders());
            } else {
                $response->setStatusCode(500);
            }
        }

        try {
            return $this->filterResponse($response, $request, $type);
        } catch (\Exception $e) {
            return $response;
        }
    }
1350994
public function handle(\Exception $ex, Request $request)
    {
        foreach ($this->callbacks as $exClass => $callback) {
            if ($ex instanceof $exClass) {
                $invoker = new Invoker();
                return $invoker->invoke($callback, [], [$ex, $request]);
            }
        }
    }
1183347
public function render($request, Exception $e)
    {
        if ($this->isServiceException($e)) {
            $e->setRequest($request);
        } elseif ($e instanceof ValidationException) {
            $e = $this->convertValidationExceptionToEntityException($e);
        } else {
            $e = $this->convertExceptionToServiceException($e);
        }

        return $this->prepareJsonResponse($e);
    }
652646
protected function handlePhpError(Throwable $e, ServerRequestInterface $request, ResponseInterface $response)
    {
        $handler = 'phpErrorHandler';
        $params = [$request, $response, $e];

        if ($this->container->has($handler)) {
            $callable = $this->container->get($handler);
            // Call the registered handler
            return call_user_func_array($callable, $params);
        }

        // No handlers found, so just throw the exception
        throw $e;
    }
287565
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        $templateEngine = $this->container['internal.template'];
        if ($templateEngine instanceof \Twig_Environment) {
            $templateEngine->addExtension(new TwigFilterExtension());
        }

        return $this->app->handle($request, $type, $catch);
    }
1321571
public function error(Request $request, Throwable $e)
    {
        $this->getLogger2FileService()->crit('error', [$request->toArray(), $e->getMessage()]);

        return true;
    }
121050
public function render($request, Exception $e)
    {
        $packageResponse = [];
        $statusCode = 500;
        if (($message = $e->getMessage())) {
            $packageResponse['title'] = $message;
        }
        if ($e instanceof OAuthException) {
            $e = new AccessDeniedHttpException($e->getMessage());
        }
        if ($e instanceof HttpException) {
            $statusCode = $e->getStatusCode();
        }
        if ($e instanceof ErrorMessageBagException && $e->hasErrors()) {
            $packageResponse['errors'] = $e->getErrors();
        }

        return response()->json($packageResponse, $statusCode);
    }
814512
protected function handleError(Exception $e)
    {
        if($this->isCli){
            $errorCode = $e->getCode();
            exit((empty($errorCode)) ? 1 : $errorCode);	//exit the program with an error
        }
        else {
            throw new Exception($e->getMessage());
        }
    }
416423
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        $filterResponse = new FilterResponse($request);
        $this->eventDispatcher->dispatch(KernelEvents::FILTER_REQUEST, $filterResponse);

        $response = $filterResponse->getResponse();
        if ($response instanceof Response) {
            return $response;
        }

        $controller = $request->attributes->get('_controller');
        if (!$controller) {
            throw new \InvalidArgumentException('Controller is not valid.');
        }

        $action = $request->attributes->get('_action');
        if (!$action) {
            throw new \InvalidArgumentException('Action method is not valid.');
        }

        $request->attributes->remove('_controller');
        $request->attributes->remove('_action');
        $parameters = $request->attributes->get('_parameters', []);
        if (!empty($parameters)) {
            $request->attributes->remove('_parameters');
        }

        $filterController = new FilterController($controller);
        $this->eventDispatcher->dispatch(KernelEvents::FILTER_CONTROLLER, $filterController);

        try {
            $response = call_user_func_array([$controller, $action], array_merge($parameters, [$request]));
        } catch (ResourceNotFoundException $e) {
            $response = new Response('Not found!', Response::HTTP_NOT_FOUND);
        }

        if ($response instanceof Response) {
            $filterResponse->setResponse($response);
            $this->eventDispatcher->dispatch(KernelEvents::FILTER_RESPONSE, $filterResponse);

            return $filterResponse->getResponse();
        }

        throw new \InvalidArgumentException(sprintf('The controller must return a "\Symfony\Component\HttpFoundation\Response" object'));
    }
1273652
public function render($request, Exception $e)
    {
        if (app()->environment() == 'testing') {
            throw $e;
        }
        if ($e instanceof NotFoundHttpException) {
            if ($request->method() == "GET") {
                return array_key_exists('extension', pathinfo(array_key_exists('path', $parsed = parse_url($request->url()))
                        ? $parsed['path']
                        : null))
                    ? errors(['Not Found'], 404)
                    : html()->generate(); 
            } 
            return errors(['Not Found'], 404);
        }
        if ($e instanceof MethodNotAllowedHttpException) {
            if ($request->method() == "GET") {
                return html()->generate();
            }  
            return parent::render($request, $e);          
        }
        if (app()->environment() == 'local') {
            return errors([$e->getMessage(), $e->getFile() . ': line ' . $e->getLine()], 500);
        }
        return errors([$e->getMessage()], 500);
    }
1050441
public static function wrapException(RequestInterface $request, \Exception $e)
    {
        return $e instanceof RequestException
            ? $e
            : new RequestException($e->getMessage(), $request, null, $e);
    }
98751
public function exception($e) {
        $type = "system";
        if (isset($_GET['type'])) {
            $type = $_GET['type'];
        }
        switch ($type) {
        case 'dapi':
        case 'api':
            $this->exception[] = $e;
            break;
        case 'page':
        default:
            require __DIR__ . '/exception.php';
            break;
        }
    }
332912
public static function sendException(\Exception $e, ServiceRequestInterface $request = null)
    {
        $response = static::exceptionToServiceResponse($e);

        return ResponseFactory::sendResponse($response, $request);
    }
896732
public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException || $e instanceof NotFoundHttpException) {
            return $this->respondNotFound(
                ApiResponse::CODE_NOT_FOUND,
                $e->getMessage()
            );
        }

        $data = [];
        $status = 500;

        if (env('APP_DEBUG')) {
            $data = [
                'exception' => \get_class($e),
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ];
        }


        if ($this->isHttpException($e)) {
            // Grab the HTTP status code from the Exception
            $status = $e->getStatusCode();
        }

        return $this->setStatusCode($status)
            ->respondWithError(
                ApiResponse::CODE_API_ERROR,
                'API internal error occurred. Please contact support for details.',
                $data
            );
    }
1330477
public final function handle(\Symfony\Component\HttpFoundation\Request $request, $type = self::MASTER_REQUEST, $catch = true) {
		// Set up environment
		$this->setUpEnvironment();

		// Init request stack and request
		$this->requestStack = new \Symfony\Component\HttpFoundation\RequestStack;
		$this->requestStack->push($request);

		// Init response from HttpFoundation
		$this->response = \Symfony\Component\HttpFoundation\Response::create()->prepare($this->requestStack->getCurrentRequest());

		// Start session
		$this->startSessionHandler();

		// Request context for routing
		$context = new \Symfony\Component\Routing\RequestContext();
		$context->fromRequest($this->requestStack->getCurrentRequest());

		// Setup routing
		$this->setUpRouting($context);

		// Setup twig
		$this->setUpTwig();

		// Allow access to symfony component form views
		$this->templateRender->addGlobal("request", $this->requestStack->getCurrentRequest());
		$this->templateRender->addGlobal("response", $this->response);
		$this->templateRender->addGlobal("routing", $this->routing);
		$this->templateRender->addGlobal("session", $this->session);
		$this->templateRender->addGlobal("flash", $this->session->getFlashBag());

		// Pre hook
		$this->preApplicationStart();

		// Find controller and action
		try {
			// Match path
			$currentRoute = $this->routing->match($this->requestStack->getCurrentRequest()->getPathInfo());
		} catch ( \Symfony\Component\Routing\Exception\ResourceNotFoundException $e ) {
			// Use default route
			$currentRoute = $this->defaultRoute;
		}

		// Set action
		if ( !isset( $currentRoute['_action'] ) )
			$currentRoute['_action'] = 'index';

		// Set request parameters
		$this->requestStack->getCurrentRequest()->attributes = new \Symfony\Component\HttpFoundation\ParameterBag($currentRoute);

		// Try to load the requested controller and action
		$data = $this->performAction($currentRoute['_controller'], $currentRoute['_action']);

		// Render json directly
		if ( $this->response instanceof \Symfony\Component\HttpFoundation\JsonResponse )
			return $this->response;

		// Render template
		if ( !isset( $this->response->template ) || false !== $this->response->template ):
			// Generate template name if not set
			if ( !isset( $this->response->template ) )
				$this->response->template = strtolower($currentRoute['_controller'] . '/' . $currentRoute['_action']);

			// Load and render template
			$data = $this->templateRender->loadTemplate($this->response->template . '.html.twig')->render($data);
		endif;

		// Add content
		$this->response->setContent($data);

		// Return response
		return $this->response;
	}
1062300
public function handleException(Throwable $e): void
    {
        $exceptionHandlerPath = null;

        if (($module = Application::getCurrentModule()) !== null) {
            $exceptionHandlerPath = Application::getModulePath($module) . 'controllers/ExceptionHandler.php';
            if (!is_file($exceptionHandlerPath)) {
                $exceptionHandlerPath = Application::getApplicationPath('controllers/ExceptionHandler.php');
            }
        } else {
            $exceptionHandlerPath = Application::getApplicationPath('controllers/ExceptionHandler.php');
        }

        if (is_file($exceptionHandlerPath)) {
            require_once $exceptionHandlerPath;
            $exceptionHandler = new \ExceptionHandler($e);

            if ($exceptionHandler instanceof ResponseExceptionHandler) {
                $exceptionHandler->exec();
            } else {
                $routeException = new ServerException('Your ExceptionHandler is not instance of ResponseExceptionHandler, can not continue');
                Log::emergency($routeException);
                Application::terminateWithError('Your ExceptionHandler is not instance of ResponseExceptionHandler, can not continue');
            }
        } else {
            $exceptionHandler = new ResponseExceptionHandler($e);
            $exceptionHandler->exec();
        }
    }
1035668
private function handleException($app, Exception $e)
    {
        $status = $e->getCode();
        $statusText = \Slim\Http\Response::getMessageForCode($status);

        if ($statusText === null) {
            $status = 500;
            $statusText = 'Internal Server Error';
        }

        $app->response->setStatus($status);
        $app->response->headers->set('Content-Type', 'application/json');
        $app->response->setBody(json_encode(array(
            'status' => $status,
            'statusText' => preg_replace('/^[0-9]+ (.*)$/', '$1', $statusText),
            'description' => $e->getMessage(),
        )));

        $app->response()->finalize();

        return $app->response();
    }