PHP: \Exception or Exception inside a namespace
exception, php
Solution
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) { ...
Problem
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"; } ```