Check debug status and throw an Exception based on the existing one

@param \Cake\Controller\Exception\SecurityException|null $exception Additional debug info describing the cause
@throws \Cake\Http\Exception\BadRequestException
@return void
340047
protected function _throwException($exception = null)
    {
        if ($exception !== null) {
            if (!Configure::read('debug') && $exception instanceof SecurityException) {
                $exception->setReason($exception->getMessage());
                $exception->setMessage(self::DEFAULT_EXCEPTION_MESSAGE);
            }
            throw $exception;
        }
        throw new BadRequestException(self::DEFAULT_EXCEPTION_MESSAGE);
    }
190849
public function handleException(\Exception $exception) {
    // get error level
    $logFunction = 'error';
    if ($exception instanceof ApplicationException) {
      $logFunction = $exception->getError()->getLevel() == ApplicationError::LEVEL_WARNING ?
              'warn' : 'error';
    }
    self::$logger->$logFunction($exception);

    try {
      if (ObjectFactory::getInstance('configuration') != null) {
        // rollback current transaction
        $persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
        $persistenceFacade->getTransaction()->rollback();

        // redirect to failure action
        if ($this->request) {
          $error = ApplicationError::fromException($exception);
          $this->request->addError($error);
          $this->response->addError($error);
          $this->request->setAction('failure');
          $this->response->setAction('failure');
          $this->response->setStatus($error->getStatusCode());
          ObjectFactory::getInstance('actionMapper')->processAction($this->request, $this->response);
          return;
        }
      }
      throw $exception;
    }
    catch (\Exception $ex) {
      self::$logger->error($ex->getMessage()."\n".$ex->getTraceAsString());
    }
  }
1098955
public function handleException($exception)
    {
        if ($exception instanceof ExitException) {
            return;
        }

        $this->exception = $exception;

        // disable error capturing to avoid recursive errors while handling exceptions
        $this->unregister();

        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
        // HTTP exceptions will override this value in renderException()
        if (PHP_SAPI !== 'cli') {
            http_response_code(500);
        }

        try {
            $this->logException($exception);
            if ($this->discardExistingOutput) {
                $this->clearOutput();
            }
            $this->renderException($exception);
            if (!YII_ENV_TEST) {
                $this->profiler->flush();
                $this->flushLogger();
                exit(1);
            }
        } catch (\Throwable $e) {
            // another exception could be thrown while displaying the exception
            $this->handleFallbackExceptionMessage($e, $exception);
        }

        $this->exception = null;
    }
581342
public function throwServiceExceptionFromRequestException(RequestException $exception)
    {
        $exceptionClass = ExceptionInterface::class;

        if ($exception->hasResponse() && $exception->getResponse()->hasHeader('X-WS-ErrorCode')) {
            $exceptionClass = $this->getServiceException($exception->getResponse()->getHeaderLine('X-WS-ErrorCode'));
        }
        if ($exceptionClass !== ExceptionInterface::class) {
            throw new $exceptionClass();
        }

        throw new ServerException('Unknown error occurred', 0, $exception);
    }
137435
public static function exception_handler(\Exception $exception) {
		global $CFG, $USR;
		$errcode = $exception->getCode();
		$errmsg = $exception->getMessage();
		$errcodelabel = ($exception instanceof \pdyn\base\Exception)
			? $exception->get_string_from_code($errcode)
			: static::getinternalerrorlabel($errcode);
		if (\pdyn\base\Utils::is_cli_env() === true) {
			echo 'APP ERROR: '.$errcodelabel.': '.$errmsg."\n";
		} else {
			// Atlas exceptions' error codes are HTTP status codes, so send one.
			if (($exception instanceof \pdyn\base\Exception) && !empty($errcode) && !headers_sent()) {
				\pdyn\httputils\Utils::send_status_code($errcode, '', false);
			} else {
				\pdyn\httputils\Utils::send_status_code(500, '', false);
			}
			$LOG = new \pdyn\log\Logger($CFG->log_general);
			$LOG->error($errcodelabel.': '.$exception);
			if (isset($_GET['ajax'])) {
				header('Content-type: application/json');
				echo json_encode(['result' => 'fail', 'msg' => $errcodelabel.': '.$errmsg]);
			} else {
				$debugmode = (!empty($CFG) && (bool)$CFG->get('core', 'debugmode', false) === true) ? true : false;
				$isadmin = (!empty($USR) && $USR->is_admin === true) ? true : false;
				$backtrace = ($isadmin === true || $debugmode === true)	? static::format_backtrace($exception->getTrace()) : null;
				static::write_error_html($errcodelabel, $errmsg, $errcode, $backtrace);
			}
		}
		die();
	}
791033
public function handleException($exception, $request, $response){
        // send a debug mail with the exception
        if(!$this->debug && !in_array(get_class($exception), $this->_skipExceptions))
            $this->_email('Website Exception', Misc::dump($exception, $exception->getMessage(), true));

        // continue with exception handle logic
        return parent::handleException($exception, $request, $response);
    }
334636
protected function logException(\Exception $exception): void
    {
        if (!$this->logger) {
            return;
        }

        $message = sprintf(
            'Exception thrown when handling an exception (%s: %s at %s line %s)',
            get_class($exception),
            $exception->getMessage(),
            $exception->getFile(),
            $exception->getLine()
        );

        $this->logger->log($this->level, $message, [
            'exception' => $exception,
        ]);
    }
1348506
public function fail($exception = null)
    {
        if ($this->job) {
            FailingJob::handle($this->job->getConnectionName(), $this->job, $exception);
        }
    }
416964
protected function _logException(Exception $exception) {
		if ($this->is404($exception)) {
			$level = LOG_ERR;
			Log::write($level, $this->_getMessage($exception), ['404']);
			return false;
		}
		return parent::_logException($exception);
	}
819283
protected function handleException(\Exception $exception)
    {
        $this->outputLine('<error>%s</error>', [$exception->getMessage()]);
        $this->outputLine();
        $this->outputLine('The exception details have been logged to the Flow system log.');
        $message = $this->throwableStorage->logThrowable($exception);
        $this->outputLine($message);
        $this->logger->error($message, LogEnvironment::fromMethodName(__METHOD__));
        $this->quit(1);
    }
448325
public function isValid( &$exception = null )
    {
        $exception = null;
        // have we validated this before?
        if( $this->isValid === null ) {
            $this->decoded = @json_decode( $this->json, true );
            // have error?
            if( null === $this->decoded and JSON_ERROR_NONE !== $lastError = json_last_error() ) {
                // yep
                $this->isValid = new BadJsonException( $this->json, $lastError );
                $exception = $this->isValid;
            } else {
                // nope
                $this->isValid = true;
            }
        // is the isValid propety a exception
        } elseif ( $this->isValid !== true ) {
            $exception = $this->isValid;
        }

        return $this->isValid === true;
    }
910927
public function setException(\Exception $exception = null)
    {
        $this->exception = $exception;
        $this->result = self::FAILED;
    }
230047
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $this->dispatcher->dispatch(self::API_GUARD_FAILED, new AuthFailedEvent($request, $exception));

        return $this->removeAuthCookieFromResponse(new Response('Authentication Failed', Response::HTTP_FORBIDDEN));
    }
1168309
public function exception($exception)
    {
        try {
            foreach ($this->handlers as $handler) {
                $handler($exception);
            }
        } catch (\Throwable $e) {
            $msg = "Infinity loop in exception & error handler. \nMessage:\n" . $e;

            if ($this->app->get('system.debug')) {
                exit($msg);
            }

            exit($e->getMessage());
        }

        exit();
    }
205066
public function handleException($exception)
    {
        // Walk the registered handlers in the reverse order
        // they were registered, and pass off the exception
        $inspector = $this->getInspector($exception);

        // Capture output produced while handling the exception,
        // we might want to send it straight away to the client,
        // or return it silently.
        $this->system->startOutputBuffering();

        // Just in case there are no handlers:
        $handlerResponse = null;
        $handlerContentType = null;

        foreach (array_reverse($this->handlerStack) as $handler) {
            $handler->setRun($this);
            $handler->setInspector($inspector);
            $handler->setException($exception);

            // The HandlerInterface does not require an Exception passed to handle()
            // and neither of our bundled handlers use it.
            // However, 3rd party handlers may have already relied on this parameter,
            // and removing it would be possibly breaking for users.
            $handlerResponse = $handler->handle($exception);

            // Collect the content type for possible sending in the headers.
            $handlerContentType = method_exists($handler, 'contentType') ? $handler->contentType() : null;

            if (in_array($handlerResponse, [Handler::LAST_HANDLER, Handler::QUIT])) {
                // The Handler has handled the exception in some way, and
                // wishes to quit execution (Handler::QUIT), or skip any
                // other handlers (Handler::LAST_HANDLER). If $this->allowQuit
                // is false, Handler::QUIT behaves like Handler::LAST_HANDLER
                break;
            }
        }

        $willQuit = $handlerResponse == Handler::QUIT && $this->allowQuit();

        $output = $this->system->cleanOutputBuffer();

        // If we're allowed to, send output generated by handlers directly
        // to the output, otherwise, and if the script doesn't quit, return
        // it so that it may be used by the caller
        if ($this->writeToOutput()) {
            // @todo Might be able to clean this up a bit better
            if ($willQuit) {
                // Cleanup all other output buffers before sending our output:
                while ($this->system->getOutputBufferLevel() > 0) {
                    $this->system->endOutputBuffering();
                }

                // Send any headers if needed:
                if (Misc::canSendHeaders() && $handlerContentType) {
                    header("Content-Type: {$handlerContentType}");
                }
            }

            $this->writeToOutputNow($output);
        }

        if ($willQuit) {
            // HHVM fix for https://github.com/facebook/hhvm/issues/4055
            $this->system->flushOutputBuffer();

            $this->system->stopExecution(1);
        }

        return $output;
    }
1151065
public function handleException(\Exception $exception)
    {
        $response = null;
        $template_controller = '\\MicroCMS\\Controller\\TemplateController';
        $error_controller = '\\MicroCMS\\Controller\\ErrorController';

        // If production (kernel.env = 'prod') we'll attempt
        // to display the 500 template if it exists, otherwise
        // we'll call the last ditch method.
        if ('prod' === $this->container->getParameter('kernel.env')) {
            try {
                $template = $this->container->get('template_resolver')->resolveErrorTemplate();

                if ((false !== $template) && class_exists($template_controller)) {
                    $controller = new $template_controller();
                    $controller->setContainer($this->container);
                    $callable = array($controller, 'indexAction');
                    $response = call_user_func_array($callable, array($template));
                } elseif (class_exists($error_controller)) {
                    $callable = array(new $error_controller(), 'errorAction');
                    $response = call_user_func_array($callable, array());
                }
            } catch (\Exception $e) {
                $response = null;
            }
        } else {
            // Call our pretty stack trace generator for dev
            try {
                if (class_exists($error_controller)) {
                    $callable = array(new $error_controller(), 'displayTraceAction');
                    $response = call_user_func_array($callable, array($exception));
                }
            } catch (\Exception $e) {
                $response = null;
            }
        }

        if (!$response) {
            $response = new Response('Error - 500');
        }

        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);

        return($response);
    }
183013
private function logException(Exception $exception): void
    {
        if ($exception instanceof HttpExceptionInterface && $exception->getStatusCode() < 500) {
            return;
        }

        $this->logger->critical(
            sprintf(
                'Uncaught PHP Exception %s: "%s" at %s line %s',
                get_class($exception),
                $exception->getMessage(),
                $exception->getFile(),
                $exception->getLine()
            ),
            ['exception' => $exception]
        );
    }