PHP Exceptions CodeIgniter - php

my code is generating ssse following error:
Fatal error: Uncaught TypeError: Argument 1 passed to
CI_Exceptions::show_exception() must be an instance of Exception,
instance of Error given, called in
C:\xampp\htdocs\gog\lib\core\Common.php on line 662 and defined in
C:\xampp\htdocs\gog\lib\core\Exceptions.php:190 Stack trace: #0
C:\xampp\htdocs\gog\lib\core\Common.php(662):
CI_Exceptions->show_exception(Object(Error)) #1 [internal function]:
_exception_handler(Object(Error)) #2 {main} thrown in C:\xampp\htdocs\gog\lib\core\Exceptions.php on line 190
The line of the codes described is these:
function _exception_handler(Throwable $exception)
{
$_error =& load_class('Exceptions', 'core');
$_error->log_exception('error', 'Exception: '.$exception->getMessage(), $exception->getFile(), $exception->getLine());
// Should we display the error?
if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors')))
{
$_error->show_exception($exception); //line 662
}
exit(1); // EXIT_ERROR
}
public function show_exception(Exception $exception) //line 190
{
$templates_path = config_item('error_views_path');
if (empty($templates_path))
{
$templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR;
}
$message = $exception->getMessage();
if (empty($message))
{
$message = '(null)';
}
if (is_cli())
{
$templates_path .= 'cli'.DIRECTORY_SEPARATOR;
}
else
{
set_status_header(500);
$templates_path .= 'html'.DIRECTORY_SEPARATOR;
}
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include($templates_path.'error_exception.php');
$buffer = ob_get_contents();
ob_end_clean();
echo $buffer;
}
Someone can pinpoint my problem ?

No CodeIgniter version has that _exception_handler() signature. This is what happens when you modify stock framework files.
Download a fresh copy of the latest CodeIgniter and replace yours with it.

You call show_exception(Exception $exception) from within _exception_handler(Throwable $exception). Since the former takes an Exception as argument, you cannot give it a Throwable, as you do in line 662. Exception implements the Throwable interface, but that does not guarantee all Throwables to be Exceptions (e. g. they could be of type Error).
Replace _exception_handler(Throwable $exception) with _exception_handler(Exception $exception), or change show_exception(Exception $exception) to show_exception(Throwable $exception), and change the method bodies accordingly if needed.

Related

CakePHP : Monolog package throw runtime exception and application stop working

composer.json packages as below,
"monolog/monolog": "~1.25.4",
"newrelic/monolog-enricher": "^1.0",
Below file is throwing run time exception,
vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php
<?php
namespace Monolog\Handler\Curl;
class Util
{
private static $retriableErrorCodes = array(
CURLE_COULDNT_RESOLVE_HOST,
CURLE_COULDNT_CONNECT,
CURLE_HTTP_NOT_FOUND,
CURLE_READ_ERROR,
CURLE_OPERATION_TIMEOUTED,
CURLE_HTTP_POST_ERROR,
CURLE_SSL_CONNECT_ERROR,
);
/**
* Executes a CURL request with optional retries and exception on failure
*
* #param resource $ch curl handler
* #throws \RuntimeException
*/
public static function execute($ch, $retries = 5, $closeAfterDone = true)
{
while ($retries--) {
if (curl_exec($ch) === false) {
$curlErrno = curl_errno($ch);
if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) {
$curlError = curl_error($ch);
if ($closeAfterDone) {
curl_close($ch);
}
throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrno, $curlError));
}
continue;
}
if ($closeAfterDone) {
curl_close($ch);
}
break;
}
}
}
if a runtime error occurs, we don't want to stop application execution to add a log.
How can I handle such a situation?
I tried to overwrite class vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php
add the below code in the composer.json file
"autoload": {
"psr-4": {
"Monolog\\Handler\\Curl\\" : "lib/MonologCurl",
}
}
created the same Util.php class in lib/MonologCurl directory to use modified code
and run composer dump-autoload
it is throwing an error as below
Fatal error: Uncaught Error: Class 'Monolog\Handler\Curl\Util' not found in /test/instances/fd/local/vendor/newrelic/monolog-enricher/src/Handler.php:138 Stack trace: #0 /test/instances/fd/local/vendor/newrelic/monolog-enricher/src/api1/Handler.php(53): NewRelic\Monolog\Enricher\AbstractHandler->sendBatch('[{"message":"St...') #1 /test/instances/fd/local/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php(92): NewRelic\Monolog\Enricher\Handler->handleBatch(Array) #2 /test/instances/fd/local/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php(108): Monolog\Handler\BufferHandler->flush() #3 [internal function]: Monolog\Handler\BufferHandler->close() #4 {main} thrown in /test/instances/fd/local/vendor/newrelic/monolog-enricher/src/Handler.php on line 138
what should be best solution?

Unknown error when running command line Phalcon app

I'm trying to run a command-line task, and my cli.php file is giving me this error:
PHP Notice: Array to string conversion in /var/www/htdocs/classschedule/app/cli.php on line 23
PHP Fatal error: Uncaught RuntimeException: Call to undefined method ::gettaskname() in /var/www/htdocs/classschedule/app/cli.php:23
Stack trace:
#0 /var/www/htdocs/classschedule/app/cli.php(23): Phalcon\Cli\Console->handle(Array)
#1 {main}
thrown in /var/www/htdocs/classschedule/app/cli.php on line 23
Here is my cli.php
include '/var/www/common/dump.php';
require 'config/bootstrap.php';
$DI->get('dispatcher')->setDefaultNamespace('Task');
$DI->get('dispatcher')->setNamespaceName('Task');
$Console = new \Phalcon\CLI\Console();
$Console->setDI($DI);
$arguments = [];
foreach($argv as $k => $arg) {
if($k == 1) {
$arguments['task'] = $arg;
} elseif($k == 2) {
$arguments['action'] = $arg;
} elseif($k >= 3) {
$arguments['params'][] = $arg;
}
}
try{
$Console->handle($arguments); // <-- This is line 23
}
catch(\Phalcon\Exception $e){
echo $e->getMessage();
exit(255);
}
I have no idea why either the Notice or Fatal error are getting generated. This file is almost identical to the cli.php for another app I have, that runs just fine. Even taking out the foreach() still causes the error.
Edit:
Bootstrap.php
Config.php
Solved
Solution:
My DI, Dispatcher, and Router were all MVC versions instead of their CLI equivalents. Changing them fixed the problem - setTask() was expected in the Dispatcher.
Could you please share your config/bootstrap.php file? I tested with:
use Phalcon\Di\FactoryDefault\Cli as DI;
Parameters were read and line 23 was asking for MainTask handler class (no error).
This is the code I tested:
use Phalcon\Loader;
use Phalcon\Di\FactoryDefault\Cli as CliDI;
$DI = new CliDI();
$loader = new Loader();
$loader->registerNamespaces(
[
'Task' => __DIR__ . '/tasks',
]
);
$loader->register();
$Console = new \Phalcon\CLI\Console();
$Console->setDI($DI);
$arguments = [];
foreach($argv as $k => $arg) {
if($k == 1) {
$arguments['task'] = $arg;
} elseif($k == 2) {
$arguments['action'] = $arg;
} elseif($k >= 3) {
$arguments['params'][] = $arg;
}
}
try{
$Console->handle($arguments);
}
catch(\Phalcon\Exception $e){
echo $e->getMessage();
exit(255);
}
And MainTask.php:
namespace Task;
use Phalcon\Cli\Task;
class MainTask extends Task
{
public function mainAction()
{
echo 'This is the default task and the default action' . PHP_EOL;
}
public function testAction(array $params)
{
echo sprintf('hello %s', $params[0]);
echo PHP_EOL;
echo sprintf('best regards, %s', $params[1]);
echo PHP_EOL;
}
}
$Console->handle($arguments); // <-- This is line 23
It seems that this line is expecting a string and you're passing an array.
Maybe phalcon is not handling this case well and can't instantiate some other object on which it tries to call gettaskname on.

"An error occurred while handling another error: yii\web\HeadersAlreadySentException"

I am trying to submit a comment on a guestbook application based on the Yii 2 Framework. On localhost on my PC works everything fine, but on the shared hosting when I want to submit a comment in View, I get this error.
Here is the error:
An error occurred while handling another error:
exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /home/mahdikas/public_html/guestbook/controllers/PostController.php on line 117.' in /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/ErrorHandler.php(135): yii\web\Response->send()
#2 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/base/ErrorHandler.php(111): yii\web\ErrorHandler->renderException(Object(yii\web\HeadersAlreadySentException))
#3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\HeadersAlreadySentException))
#4 {main}
Previous exception:
exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /home/mahdikas/public_html/guestbook/controllers/PostController.php on line 117.' in /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/base/Application.php(392): yii\web\Response->send()
#2 /home/mahdikas/public_html/guestbook/web/index.php(12): yii\base\Application->run()
#3 {main}
In the postController I have this code:
public function actionAdd_comment()
{
//print_r($_POST);
$model = new \app\models\Comments;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->comment_date = date('Y-m-d H:i:s');
if ($model->save()) {
echo 'Thanks for your comment.';
} else {
echo 'Failed!';
}
}
}
which line 117 in the error is:
echo 'Thanks for your comment.';
How can I solve this problem?
Since Yii 2.0.14 you cannot echo in a controller. A response must be returned:
public function actionAdd_comment() {
$model = new \app\models\Comments();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->comment_date = date('Y-m-d H:i:s');
if ($model->save()) {
return 'Thanks for your comment.';
} else {
return 'Failed!';
}
}
}
You may also call exit at the end of your method to prevent further processing or wrap your code with ob_start() and ob_get_clean(), if you're not able to avoid echo.
public function actionAdd_comment() {
$model = new \app\models\Comments();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$this->someMagicWithEcho();
exit;
}
}
or
public function actionAdd_comment() {
$model = new \app\models\Comments();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
ob_start();
$this->someMagicWithEcho();
return ob_get_clean();
}
}
Although I accept rob006's solution as correct, I have encountered a situation where there was no echo in the controller, but I also got the error. After going through several sites looking for a solution, I discovered an alternative.
You can check the php.ini file and ensure the output buffer is enabled. If not, you can enable it by adding this line in php.ini if it does not exist:
output_buffering = on
And turn it off for just the script - the script where it is not required by either...
calling ob_end_flush(), or
calling ob_end_clean()

php multidimensional SplFixedArray declaration is throwing fatal error

I want to declare SplFixedArray(); to save memory consumption. but it is throwing fatal error.
$items=new SplFixedArray();
echo "Array Started...";
for($h=0;$h<5000;$h++)
{
for($i=0;$i<24;$i++)
{
$items[$h][$i]=$objSheet->getCellByColumnAndRow($i,$h+1)->getValue();
}
}
The same is working if do not declare new SplFixedArray();
Error:
Fatal error: Uncaught exception 'RuntimeException' with message 'Index
invalid or out of range' in /home/twa/files.php:168 Stack trace: #0
/home/twa/files.php(168): unknown() #1 {main} thrown in
/home/twa/files.php on line 168
$items=new SplFixedArray(SplFixedArray()); is also failing...
Please let me know correct syntax...
$items = new SplFixedArray(5000);
for ($h=0; $h<5000; $h++) {
$items[$h] = new SplFixedArray(24);
for ($i=0; $i<24; $i++) {
$items[$h][$i] = $objSheet->getCellByColumnAndRow($i,$h+1)->getValue();
}
}

(400) Bad Requestwhen using the permission to the library google-api-php-client

Uploading a file and immediately do permission->update:
public function sharingFile() {
$fileId = $this->file['id'];
$permissionId = $this->file['userPermission']['id'];
try {
$permission = $this->service->permissions->get($fileId, $permissionId);
$permission->setRole('writer');
$permission->setType('default');
print_r($permission);
return $this->service->permissions->update($fileId, $permissionId, $permission);
} catch (Exception $e) {
return "Error: " . $e;
}
return NULL;
}
and get an error:
Error: exception 'Google_ServiceException' with message 'Error calling PUT
https://www.googleapis.com/drive/v2/files/0B6xE_F1PfpXTbF9IdHgxbEJueEk/permissions/me:
(400) Bad Request' in Z:\home\site.com\www\google-api-php-client\src\io\Google_REST.php:66
Stack trace:
#0 Z:\home\site.com\www\google-api-php-client\src\io\Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
#1 Z:\home\site.com\www\google-api-php-client\src\service\Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest))
#2 Z:\home\site.com\www\google-api-php-client\src\contrib\Google_DriveService.php(774): Google_ServiceResource->__call('update', Array)
it may be a bug in the library?
Help, please.
Your code is trying to update permissions for the document owner and make that user a writer instead. A Drive document must have exactly one owner, so your request is invalid.

Categories