Uncaught exception with namespace - php

I am reading a book about php and I found this script that doesn't work:
namespace woo\controller {
// woo\controller\ApplicationHelper;
class ApplicationHelper {
function getOptions() {
if (!file_exists("data/woo_options_not_there.xml")) {
$r = new \woo\base\AppException("Non riesco ad aprire il file<br>");
throw new $r;
}
$options = simplexml_load_file("data/woo_options.xml");
$dsn = (string) $options->dsn;
print $dsn;
}
}
$d = (new ApplicationHelper())->getOptions();
}
namespace woo\base {
class AppException extends \Exception {
}
}
Can you help me?
This is the mistake:
Fatal error: Uncaught exception 'woo\base\AppException' in C:\xampp\htdocs\9781430260318_Chapter_12_Code\listing12.00.php:11 Stack trace: #0 C:\xampp\htdocs\9781430260318_Chapter_12_Code\listing12.00.php(20): woo\controller\ApplicationHelper->getOptions() #1 {main} thrown in C:\xampp\htdocs\9781430260318_Chapter_12_Code\listing12.00.php on line 11

So let's follow the train of logic here
We're creating the class ApplicationHelper and then instantiating it. Then, we call getOptions() which looks for an XML file and, if it doesn't find it, throws an exception.
Your code is working fine, you just forgot to catch the exception (this produces a fatal PHP error)
try {
$d = (new ApplicationHelper())->getOptions();
} catch(\woo\base\AppException $err) {
echo 'Error: ' . $err->getMessage();
}

Related

Fatal Error - Call to undefined method "Customersss::throwError()"

I created a class and try to call in a method, but however in my error log, I am getting response "Uncaught Error: Call to undefined method Customersss::throwError()", please what am I doing wrong, because I know I have created throwError(), I can't seem to be able to access the class.
Firstly the class trying to call object
$this->throwError(INVALID_DATA_TTT, "Invalid shipping fee"); //WHERE I SUSPECT ERROR IS BEING GENERATED
The full error
PHP Fatal error: Uncaught Error: Call to undefined method
Customersss::throwError() in
/home/osconliz/public_html/Osconlizapicall/customers.php:276 Stack
trace:
#0 /home/osconliz/public_html/Osconlizapicall/api.php(177): Customersss->insertNewDelivery()
#1 [internal function]: Api->create_insert_new_delivery()
#2 /home/osconliz/public_html/Osconlizapicall/rest.php(42): ReflectionMethod->invoke(Object(Api))
#3 /home/osconliz/public_html/Osconlizapicall/index.php(4): Rest->processApi()
#4 {main} thrown in /home/osconliz/public_html/Osconlizapicall/customers.php on line 276
customers.php
require_once('constants.php');
require_once('rest.php');
class Customersss {
private $id;
private $shipping_fee;
private $pickup_fee;
function setId($id){ $this->id = $id; }
function getId() { return $this->id; }
function setShipping_fee($shipping_fee){ $this->shipping_fee = $shipping_fee; }
function getShipping_fee() { return $this->shipping_fee; }
function setPickup_fee($pickup_fee){ $this->pickup_fee = $pickup_fee; }
function getPickup_fee() { return $this->pickup_fee; }
public function __construct(){
$db = new DbConnect();
$this->dbConn = $db->connect();
}
public function insertNewDelivery(){
if ($this->shipping_fee == ""){
$this->throwError(EMPTY_PARAMETER, "Empty shipping fee");
exit();
}
if ($this->shipping_fee == ""){
$this->throwError(INVALID_DATA_TTT, "Invalid shipping fee");
exit();
}
}
}
rest.php
require_once('constants.php');
class Rest {
protected $request;
protected $serviceName;
protected $param;
public function processApi(){
$api = new API;
$rMethod = new reflectionMethod('API', $this->serviceName);
if(!method_exists($api, $this->serviceName)){
$this->throwError(API_DOST_NOT_EXIST, "API does not exist");
}
$rMethod->invoke($api);
}
public function throwError($code, $message){
header("content-type: application/json");
$errorMsg = json_encode(['error' => ['status'=>$code, 'message'=>$message]]);
echo $errorMsg; exit;
}
}
constants.php
define('INVALID_DATA_TTT', 350);
define('EMPTY_PARAMETER', 404);
define('API_DOST_NOT_EXIST', 400);
define('ACCESS_TOKEN_ERRORS', 500);
api.php
require_once "customers.php";
require_once "constants.php";
class Api extends Rest {
public $dbConn;
public function __construct(){
parent::__construct();
$db = new DbConnect;
$this->dbConn = $db->connect();
}
public function create_insert_new_delivery(){
$shipping_fee= $this->validateParameter('item_category', $this->param['shipping_fee'], STRING, true);
try {
$cust = new Customersss;
} catch (Exception $e){
$this->throwError(ACCESS_TOKEN_ERRORS, $e->getMessage());
}
}
You are calling Rest::ThrowError() from Customersss class. It means your function is unreachable in this context.
To call this Rest method from the Customersss class, you can:
extend Rest to Customersss (see inheritance)
make ThrowError() a static method (see static)
Using inheritance:
class Customersss extends Rest { /* your properties/methods */ }
Using a static method:
class Rest {
static public function throwError($code, $message){ /* your code */ }
}
Callable with Rest::ThrowError()

PHP - Catch error?

I am trying to catch an error for my app in PHP any help? I'm not sure how to go about sorting this issue as I am pretty new to PHP.
Error:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function SRP\App\App::onError(), 0 passed
Code:
namespace SRP\App;
use SRP\App\Librarys\Config\Config;
class App
{
public static function boot() {
Config::loadConfig();
set_error_handler(self::onError());
if (Config::get('app.environment') === 'development') {
error_reporting(E_ALL);
}
else {
error_reporting(0);
}
}
protected static function onError($exception) {
echo 'Something went wrong.';
}
}

PHP: \Exception or Exception inside a namespace

I am trying to handle some errors in my api. However I tried some so many ways to execute what it's needed to it done?
In the code i used Exception, \Exception, another class extending to Exception, "use \Exception".
None of these options works.
What i need to do execute the block catch?
//Piece of source in the begin of file
namespace Business\Notifiers\Webhook;
use \Exception;
class MyException extends \Exception {}
//Piece of source from my class
try{
$products = $payment->getProducts();
if(count($products) == 0)
return;
$flight_id = $products[0]->flight_id;
$this->message = 'Sir, we have a new request: ';
$products = null; //Chagind it to null to force an error..
foreach($products as $product){
$this->appendAttachment(array(
'color' => '#432789',
'text' =>
"*Name:* $product->name $product->last_name \n" .
"*Total Paid:* R\$$product->price\n",
'mrkdwn_in' => ['text', 'pretext']
));
}
} catch(Exception $e){
$this->message = "A exception occurred ";
} catch(\Exception $e){
$this->message = "A exception occurred e";
} catch(MyException $e){
$this->message = "A exception occurred";
}
The accepted answer above give the real cause of the issue, but did not answer the topic
If in case someone is interested and is looking for
what is the difference between Exception and \Exception inside a namespace?
Still valid against PHP 7.3.5:
\Exception: Refer to Exception in root namespace
Exception: Refer to Exception in current namespace
PHP does not fall back to root namespace, if the class cannot be found in current name space, it emits an error.
<?php
namespace Business;
try {
throw new Exception("X"); // Uncaught Error: Class 'Business\Exception' not found
} catch (Exception $e) {
echo "Exception: " . $e->getMessage();
}
<?php
namespace Business;
class Exception extends \Exception {} // means \Business\Exception extends \Exception
$a = new Exception('hi'); // $a is an object of class \Business\Exception
$b = new \Exception('hi'); // $b is an object of class \Exception
First of all, you need to understand the difference between an exception and an error:
http://php.net/manual/en/language.exceptions.php
http://php.net/manual/en/ref.errorfunc.php
Trying to foreach over a null value will not yield an exception, but trigger an error. You can use an error handler to wrap an error in an exception, as such:
<?php
function handle ($code, $message)
{
throw new \Exception($message, $code);
}
set_error_handler('handle');
// now this will fail
try {
$foo = null;
foreach ($foo as $bar) {
}
} catch(\Exception $e) {
echo $e->getMessage();
}
However in your code, you can simply check if $products is null and if so, throw an exception:
if (!$products) {
throw new \Exception('Could not find any products')
}
foreach($products as $product) { ...

Class not found, when trying to pass class name as string, namespace issue

Here is a method, in which a string is passed, using that string an instance is created. Example method:
public function action($actionType)
{
//var_dump(new $actionType);
if (!class_exists($actionType)) {
//throw new Exception
}
if (!(new $actionType) instanceof ActionInterface) {
////throw new Exception
}
$actionType = new $actionType;
echo $actionType->doAction();
}
But I am getting an error of class not found, however when I manually write the class name or manually append the namespace this way $actionType = __namespace__ . "\\$actionType";, then error goes. Why is that happening?
Try this:
public function action($actionType) {
//var_dump(new $actionType);
if (!class_exists($actionType)) {
//throw new Exception
}
$actionType = new $actionType;
if (!($actionType instanceof ActionInterface)) {
////throw new Exception
}
echo $actionType->doAction();
}

Fatal error of method while declaring new Class

I've got this weird error.
I've got DB class and Live class. the Live class is not extends DB class.
I can't understand why when i declare the New Live this happened.
The Errors is:
Notice: Undefined property: Live::$isOff in /home/main/Database/DB.class.php on line 570
Fatal error: Call to undefined method Live::Query() in /home/main/Database/DB.class.php on line 574
This is what i got on this line:
ON DB.Class.php
public function setCharset($charset) {
if (self::$isOff){
return false;
}
self::$charset = $charset;
self::Query("SET NAMES '".$charset."'");
return self;
}
ON Live.Class.php
class Live
{
protected $PaypalLogo = '';
protected $isQA = null;
protected $siteURL = null;
public function __construct() {
DB::setCharset("utf8");//Setting charset here and that is gives Fatal Error.
if (strstr($_SERVER['SERVER_NAME'], "ba.")) {
$this->isQA = true;
$this->siteURL = "http://ba.live.com";
}
else {
$this->isQA = false;
$this->siteURL = "http://www.live.com/";
}
}
Thank you for any advice.
I found the Problem. it was because there are no instance of DB and because of this, it was take the instance of Live .

Categories