PHP:\名称空间内的异常或异常

时间:2016-10-15 21:06:14

标签: php exception

我正在尝试处理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";
    } 

2 个答案:

答案 0 :(得分:4)

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

  1. http://php.net/manual/en/language.exceptions.php
  2. http://php.net/manual/en/ref.errorfunc.php
  3. 尝试覆盖空值不会产生异常,但会触发错误。您可以使用错误处理程序将错误包装在异常中,如下所示:

    <?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仍然有效:

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

<?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