【发布时间】:2016-08-20 04:21:21
【问题描述】:
我的问题是关于在 PHP 中捕获异常的正确方法。 基于 PHP MongoDB 驱动程序随附的examples,我 已创建以下脚本:
<?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";
}
?>
该示例具有教育意义,旨在在 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
这是一种在 PHP 中捕获异常的合理方式吗?
【问题讨论】:
标签: php mongodb exception-handling try-catch