如何在 PHP 和 MongoDB 中正确捕获异常

Jan*_*nar 4 php exception-handling try-catch mongodb

我的问题是关于在 PHP 中捕获异常的正确方法。根据随附的 PHP MongoDB 驱动程序示例,我创建了以下脚本:

<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:2717");
    $query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]);     

    $rows = $mng->executeQuery("testdb.cars", $query);

    foreach ($rows as $row) {

        echo "$row->name : $row->price\n";
    }

} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";       
}

?>
Run Code Online (Sandbox Code Playgroud)

该示例具有教育意义,旨在在 PHP CLI 上运行。在 PHP CLI 中,我们在控制台上获取所有异常,但出于教学目的,我想在 try/catch 块中捕获异常。

我见过的 Java 代码比 PHP 多,因此,捕获泛型MongoDB\Driver\Exception\Exception对我来说并不好。在 Java 中,我们捕获特定的异常并针对不同类型的异常有多个 try/catch 块。

驱动程序有以下异常:

MongoDB\Driver\Exception\AuthenticationException
MongoDB\Driver\Exception\BulkWriteException 
MongoDB\Driver\Exception\ConnectionException 
MongoDB\Driver\Exception\ConnectionTimeoutException 
MongoDB\Driver\Exception\Exception 
MongoDB\Driver\Exception\ExecutionTimeoutException 
MongoDB\Driver\Exception\InvalidArgumentException 
MongoDB\Driver\Exception\LogicException 
MongoDB\Driver\Exception\RuntimeException 
MongoDB\Driver\Exception\SSLConnectionException 
MongoDB\Driver\Exception\UnexpectedValueException 
MongoDB\Driver\Exception\WriteException
Run Code Online (Sandbox Code Playgroud)

这是在 PHP 中捕获异常的犹太洁食方式吗?

Ger*_*csy 5

如何在 catch 部分放置一个 switch 语句,并通过instanceof语言结构或get_class()函数来确定异常的类型?

例如:

[...]

} catch(\Exception $e) {
   switch (get_class($e)) {
     case 'MongoDB\Driver\Exception\AuthenticationException':
       // do stuff
       break;

     case 'MongoDB\Driver\Exception\BulkWriteException':
     //etc, etc...
   }
}
Run Code Online (Sandbox Code Playgroud)

首先,我会检查 get_class() 的返回值,以确保您将结果与确切的异常名称进行比较。