douye4254 2013-12-18 17:28
浏览 42
已采纳

如何包装try catch或其他错误处理

I'm a little new to OOP in PHP. I was putting together an ip to location code from MaxMind, and wanted to wrap some error handling around it, because if you supply it with an incorrect IP address, or the database is corrupt, it'll throw a fatal error.

Most of my code is stock code, but I cannot get the error handling part correct.

Here's the stock code. The idea here is to set $countryCode = 'UN' and $countryName = 'Unknown' initially, and then, if the script works, set it to whatever depending on the Ip address supplied.

Stock Code

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;

I tried

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;

However, this is what I'm trying to do:

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;

I cant use if() here, how is this done using try catch? In all there's no need to halt the script. Let the default values of $countryCode and $countryName remain if the i[ detect does not succeed.

The code in the MaxMind script is done this way:

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

1条回答

  • dongmiyu8979 2013-12-18 17:31
    关注

    If any line within a try block throws an exception, future lines are not ran and the catch block is ran instead. So you can safely move those lines into the try block:

    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;
    

    Now, if the first line of the try block throws an exception, the other three lines won't be executed. Instead, the catch block will be executed. So that is where you can send your email to the admin.

    (If the $reader = line throws an exception, the $record = line will not be executed, nor will subsequent lines within the try block.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?