如何围绕此问题包装尝试捕获或其他错误处理


How to wrap a try catch or other error handling around this

我对PHP中的OOP有点陌生。我正在将MaxMind的IP到位置代码放在一起,并希望围绕它进行一些错误处理,因为如果您为其提供不正确的IP地址,或者数据库已损坏,它将引发致命错误。

我的大部分代码都是股票代码,但我无法正确处理错误部分。

这是股票代码。这里的想法是最初设置$countryCode = 'UN'$countryName = 'Unknown',然后,如果脚本有效,则根据提供的 IP 地址将其设置为 whatever

股份代号

require_once($_SERVER['DOCUMENT_ROOT'].''vendor'autoload.php');
use GeoIp2'Database'Reader;
$countryCode = 'UN';
$countryName = 'Unknown';
$reader = new Reader($_SERVER['DOCUMENT_ROOT'].''geoip'GeoLite2-City.mmdb');
$record = $reader->city('24.22.173.253');
$countryCode = $record->country->isoCode . '<br>'; // 'US'
$countryName = $record->country->name . '<br>'; // 'United States'
echo $countryCode;
echo $countryName;

我试过了

require_once($_SERVER['DOCUMENT_ROOT'].''vendor'autoload.php');
use GeoIp2'Database'Reader;
$countryCode = 'UN';
$countryName = 'Unknown';
try{
$reader = new Reader($_SERVER['DOCUMENT_ROOT'].''geoip'GeoLite2-City.mmdb');
}
catch(Exception $e)
  {
  echo 'Message: ' .$e->getMessage();
  }
$record = $reader->city('24.22.173.253');
$countryCode = $record->country->isoCode . '<br>'; // 'US'
$countryName = $record->country->name . '<br>'; // 'United States'
echo $countryCode;
echo $countryName;

但是,这就是我要做的:

require_once($_SERVER['DOCUMENT_ROOT'].''vendor'autoload.php');
use GeoIp2'Database'Reader;

$countryCode = 'UN';
$countryName = 'Unknown';
**If (the below is successful -> the db is successfully opened)**
$reader = new Reader($_SERVER['DOCUMENT_ROOT'].''geoip'GeoLite2-City.mmdb');
then (proceed with the below){
$record = $reader->city('24.22.173.253');
$countryCode = $record->country->isoCode . '<br>'; // 'US'
$countryName = $record->country->name . '<br>'; // 'United States'
}
else
//Send an email to the admin here
echo $countryCode;
echo $countryName;

我不能在这里使用 if(),如何使用 try catch 完成此操作?总之,没有必要停止脚本。如果 i[ 检测不成功,则保留默认值 $countryCode 和 $countryName。

MaxMind 脚本中的代码是这样完成的:

if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
            throw new 'InvalidArgumentException(
                "The value '"$ipAddress'" is not a valid IP address."
            );
        }

如果try块中的任何行引发异常,则不会运行将来的行,而是运行catch块。 因此,您可以安全地将这些行移动到try块中:

require_once($_SERVER['DOCUMENT_ROOT'].''vendor'autoload.php');
use GeoIp2'Database'Reader;
$countryCode = 'UN';
$countryName = 'Unknown';
try {
    $reader = new Reader($_SERVER['DOCUMENT_ROOT'].''geoip'GeoLite2-City.mmdb');
    $record = $reader->city('24.22.173.253');
    $countryCode = $record->country->isoCode . '<br>'; // 'US'
    $countryName = $record->country->name . '<br>'; // 'United States'
} catch(Exception $e) {
    // Send an email to the admin here instead of echo'ing $e->getMessage()
    // if that's what you want to do.
    echo 'Message: ' .$e->getMessage();
}
echo $countryCode;
echo $countryName;

现在,如果try块的第一行引发异常,则不会执行其他三行。 相反,将执行catch块。 因此,您可以在此处将电子邮件发送给管理员。

(如果$reader =行引发异常,则不会执行$record =行,也不会执行try块中的后续行。