php中弹出警告删除,PHP应用技巧:如何将代码中的通知和警告删除

【PHPChina讯】警告有时可以从一些代码中删除,当代码中弹出警告提示时,用户可进行适当选择,其中包括将它们写在错误日志中,或完全忽视。而Alexander Netkachev却有不同的解决方案——通过内建在中的例外来处理、

该编码技巧将展示如何通过try/catch语句以例外的方式来处理PHP通知和警告。

尽管这是一个很简单的方案,但却完全可以帮助用户将所有的错误信息存储在同一位置。Alexander Netkachev所提供的代码示例既展示了基本的解决方案,也展示了其复杂的一面。另外,还为不同的例外类型提供了更详细的信息。

代码如下:

function errorHandler($errno, $errstr, $errfile, $errline) {

throw new Exception($errstr, $errno);

}

set_error_handler('errorHandler');

try {

file_put_contents('cosmos:\\1.txt', 'asdf');

} catch (Exception $e) {

echo $e->getMessage();

}

The code above throws an exception because the file cannot be saved. Then the exception is caught by the try/catch statement. With a little bit of additional error processing you can create even more reliable code:class IOException extends Exception {}

function errorHandler($errno, $errstr, $errfile, $errline) {

if (false !== substr('failed to open stream', $errstr)) {

throw new IOException($errstr, $errno);

}

throw new Exception($errstr, $errno);

}

set_error_handler('errorHandler');

try {

file_put_contents('cosmos:\\1.txt', 'asdf');

} catch (IOException $e) {

echo 'IO exception: ' . $e->getMessage();

} catch (Exception $e) {

echo 'Unknown exception: ' . $e->getMessage();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值