我正在尝试处理api中的一些错误。但是我尝试了很多方法来执行它所需要的工作?
在代码中我使用Exception,\ Exception,另一个类扩展到Exception,"使用\ Exception"。 这些选项都不起作用。 我需要做什么来执行块捕获?
//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";
}
答案 0 :(得分:4)
首先,您需要了解异常和错误之间的区别:
尝试覆盖空值不会产生异常,但会触发错误。您可以使用错误处理程序将错误包装在异常中,如下所示:
<?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();
}
但是在您的代码中,您只需检查$ products是否为null,如果是,则抛出异常:
if (!$products) {
throw new \Exception('Could not find any products')
}
foreach($products as $product) { ...
答案 1 :(得分:3)
上面接受的答案给出了问题的真正原因,但没有回答主题
如果有人有兴趣并正在寻找
命名空间中的Exception和\ Exception有什么区别?
对于PHP 7.3.5仍然有效:
<?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