PHP:\ Exception或名称空间内的Exception

Gui*_*res 5 php exception

我正在尝试处理我的api中的一些错误。但是,我尝试了许多方法来执行所需的操作?

在代码中,我使用了Exception \ Exception,这是另一个扩展到Exception的类“ use \ 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";
    } 
Run Code Online (Sandbox Code Playgroud)

Mic*_*tch 16

上面接受的答案给出了问题的真正原因,但没有回答主题

如果有人感兴趣并正在寻找

命名空间内的 Exception 和 \Exception 之间有什么区别?

对 PHP 7.3.5 仍然有效:

  1. \Exception: 参考命名空间中的异常
  2. 异常:参考当前命名空间中的异常
  3. PHP 不会回退到根命名空间,如果在当前命名空间中找不到该类,则会发出错误。

<?php
namespace Business;
try {
    throw new Exception("X"); //  Uncaught Error: Class 'Business\Exception' not found
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
<?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
Run Code Online (Sandbox Code Playgroud)


mot*_*elu 6

首先,您需要了解异常和错误之间的区别:

  1. http://php.net/manual/en/language.exceptions.php
  2. http://php.net/manual/en/ref.errorfunc.php

尝试 foreach 空值不会产生异常,但会触发错误。您可以使用错误处理程序将错误包装在异常中,如下所示:

<?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();
}
Run Code Online (Sandbox Code Playgroud)

但是在您的代码中,您可以简单地检查 $products 是否为空,如果是,则抛出异常:

if (!$products) {
    throw new \Exception('Could not find any products')
}
foreach($products as $product) { ...
Run Code Online (Sandbox Code Playgroud)

  • 从本质上讲,警告只是 E_WARNING 级别的错误。无论哪种方式,代码都可以工作。您可以通过指定 set_error_handler() 函数的第二个参数来监视某些类型的错误 - http://php.net/manual/en/function.set-error-handler.php (3认同)