PHP Recoverable fatal error - Catch not working - php

I have code that I am trying to update to work with at least PHP version 7.3 and even when I put in a try catch statement I still get a fatal error thrown.
Below is the function that puts Objects into the Session. line causing error: $objects[$i] = $Object;
function findObjectsLIB() {
$objects = ""; $i = 0;
foreach ($_SESSION['Objects'] as $o => $Object) {
$className = get_class($Object);
if (!empty($className)) {
try {
$objects[$i] = $Object;
$i++;
} catch(Exception $err) {
$_SESSION['errors'] .= $err->getMessage();
}
}
}
return $objects;
}
I am getting this error.
PHP Recoverable fatal error: Object of class Extra could not be
converted to string.
How it not being caught?
For one it is strange that it is not being caught and why is it having an issue in 7.3 but not 5.6?

Related

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.

Show Exception message when passing invalid argument type

I have a function
<?php
public function setStatusToReadyToShip(array $order_item_ids, $delivery_type, $shipping_provider = '', $tracking_number = '')
{
//code
}
Now I want the caller to call this method by providing $order_item_ids in array format.
One way i could do is to check is_array($order_item_ids) and send the error to the caller. But i am to utilize Type Hinting. How would i send the user the error response when using type hinting. As currently it crashes the application and says
exception 'ErrorException' with message 'Argument 1 passed to Class::SetStatusToReadyToShip() must be of the type array, integer given
I am not familiar with the try catch stuff that much. I tried placing try-catch inside this function so that it does not crash the application but the same output received.
Thanks
It is Catchable fatal error with constant E_RECOVERABLE_ERROR
There are 2 methods to solve this problem (at least two).
Create your own exception handler and set it as main error handler.
Make type validation in your function, and throw exception from it:
function setStatusToReadyToShip($order_item_ids, $delivery_type, $shipping_provider = '', $tracking_number = '')
{
if (!is_array($order_item_ids)) {
throw new InvalidArgumentException('First parameter of function '.__FUNCTION__.' must be array');
}
// your code
}
and than catch it
try {
setStatusToReadyToShip(5, 6);
} catch(InvalidArgumentException $e) {
var_dump($e->getMessage());
}
<?php
class YourClass {
public static function _init() {
set_error_handler('YourClass::_typeHintHandler');
}
public static function _typeHintHandler($errorCode, $errorMessage) {
throw new InvalidArgumentException($errorMessage);
}
public function setStatusToReadyToShip(array $order_item_ids, $delivery_type, $shipping_provider = '', $tracking_number = '')
{
}
}
YourClass::_init();
$yo = new YourClass();
try {
$yo->setStatusToReadyToShip("test");
}catch(Exception $e) {
print $e->getMessage();
}

Is there any way to catch eval fatal error in php?

Im executing the list of php codes via eval, If there is any error in code i want to display this code have fatal error/parse error.
is there any way to give custom message for fatal error or any other error
My code is like this :
$output = [];
foreach($codes as $key => $res) {
if(eval($res['code'])) {
eval($res['code']);
$output[$key] = $result;
} else {
$output[$key] = "Fatal error in code";
}
}
var_dump($output);
There is a way! Write the code to a file, using php -l in the eval, then delete the file. See my answer for example code:
Is there any way to catch fatal error using eval()?
The trick is to expect Throwable:
try {
...
#eval(...);
...
} catch(Throwable $t) {
...
}

I can not catch exception in Yii framework

I am using Yii framework and have written code below. When there is no entry for a specific id it gives Error: Call to a member function delete() on a non-object which is a yii\base\ErrorException indicated in debug mode. The problem is that I am not able to catch this exception despite my inclusion of yii\base\ErrorException and specify it catch block. What is the problem here?
use yii\base\ErrorException;
try {
$model = BranchUser::findOne($_GET['id']);
$model->delete();
return $this->redirect(['index']);
} catch (ErrorException $e) {
return $this->redirect(['site/error']);
// Error, rollback transaction
throw $e;
// print_r($model->getErrors());
}
That is a fatal error and it is not possible to recover from it.
You should check that $model is something else than null before you try to use it.
if ($model === null) {
return $this->redirect(['site/error']);
}
Such errors are catchable in PHP 7.0, so that's good.

XML Exception in PHP not being caught

My code snippet is below - as you can see, I have a try-catch block, but inspite of this, I still get an uncaught exception that terminates the entire application. What am I missing?
try {
$cakeXml = simplexml_load_string($xml);
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
2014-12-16 22:45:12 Error: Fatal Error (1): Call to a member function xpath() on a non-object
2014-12-16 22:45:12 Error: [FatalErrorException] Call to a member function xpath() on a non-object
If you read the error message more-carefully, you will see that it is not dieing on an Exception, but on a Fatal Error. A try/catch statement cannot catch a fatal error in PHP, as there is no way to recover from a fatal error.
As for solving this issue, your error is telling you $cakeXml is a non-object. One solution would be to do something like this.
try {
$cakeXml = simplexml_load_string($xml);
if (!is_object($cakeXml)) {
throw new Exception('simplexml_load_string returned non-object');
}
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
DOMXPath methods i.e. xpath or evaluate does not throw exceptions. Hence, you will need to explicitly validate and throw the exception.
See below code snippet:
$xml_1= "";
try {
$cakeXml = simplexml_load_string($xml_1);
if ( !is_object($cakeXml) ) {
throw new Exception(sprintf('Not an object (Object: %s)', var_export($cakeXml, true)));
} else {
$parseSuccess = $cakeXml->xpath('//pages');
print('<pre>');print_r($parseSuccess);
}
} catch (Exception $ex) {
echo 'Caught exception: ', $ex->getMessage(), "\n";
}

Categories