如何包装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."
            );
        }
php

1个回答



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

  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-&gt; city('24 .22.173.253');
$ countryCode = $ record-&gt; country-&gt; isoCode。 '&LT峰; br&GT;'; //'US'
$ countryName = $ record-&gt; country-&gt; name。 '&LT峰; br&GT;'; //'美国'
}捕获(例外$ e){
//向管理员发送电子邮件而不是回复$ e-&gt; getMessage()
//如果这是你想要的 do。
echo'Fessage:'。$ e-&gt; getMessage();
}

echo $ countryCode;
echo $ countryName;
</ code> </ pre>

现在,如果 try </ code>块的第一行抛出异常,则不会执行其他三行。 而是执行 catch </ code>块。 这就是您可以将电子邮件发送给管理员的地方。</ p>

(如果 $ reader = </ code>行抛出异常, $ record = < / code>行将不</ em>执行,尝试</ code>块中的后续行也不会执行。)</ p>
</ div>

展开原文

原文

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.)

dtzhfb4869
dtzhfb4869 正确 - 如果$ reader =行成功,但是$ record =行抛出异常,那么catch块将在它之后执行,后续的两行代码将不会被执行。
6 年多之前 回复
drnl10253
drnl10253 我觉得你是对的。 所以我快到了。 那么不需要另外试一下$ record吗?
6 年多之前 回复
dtmbc1606
dtmbc1606 你不明白,诺曼......在我在这里编写的代码中,-indeed-,如果$ reader =行没有抛出异常,则只会执行$ record =行。 如果$ reader =行抛出异常,PHP将在执行任何其他代码行之前跳出try块并进入catch块。
6 年多之前 回复
duanfang5849
duanfang5849 就像我做的一样。 事情是,我也试图添加一个尝试围绕$ record =部分的尝试。 因此,只有$ reader = part成功时,$ record = part才会运行。
6 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问