一个php 异常处理程序

一个php的异常处理程序,功能很简单当发生重大错误时,写日志并友好提示用户.
代码:

<?php
//exceptionHandle.php xiecongwen 20140620
//define('DEBUG',true);
/**
* Display all errors when APPLICATION_ENV is development.
*/
if (defined('DEBUG')) {
error_reporting(E_ALL);
ini_set("display_errors", 1);
}
if(!defined('DEBUG')){
/**
* 当发生重大错误时 写日志 并友好提示用户
* (PS:只所以将代码写在这里,是因为在其他地方注册时,出现问题无法调用配置函数.待完善...)
*/
function shutdownHandler()
{
/**
* 写日志 此处直接写在根目录下shutdownlog.txt
*/
$lasterror = error_get_last();
if($lasterror){
$error = strval(date("Y-m-d h:i:s")).'=>'."[SHUTDOWN] lvl:" . $lasterror['type'] . " | msg:" . $lasterror['message'] . " | file:" . $lasterror['file'] . " | ln:" . $lasterror['line']."\n";
file_put_contents('./log/'.date("Ymd").'shutdownlog.txt',$error,FILE_APPEND);
//友好提示用户
ob_end_clean();
die('对不起,我出错了!');
}
}
register_shutdown_function('shutdownHandler');
}
if(!defined('DEBUG')){
 
function errorHandler($errno, $errstr = '', $errfile = '', $errline = 0)
{
//写日志
$exception = new \ErrorException($errstr, 0, $errno, $errfile, $errline);
$msg = strval(date("Y-m-d h:i:s")).'=>'.'Type:'.getErrTypeName($errno).' '.getMsg($exception);
file_put_contents('./log/'.date("Ymd").'error.txt',$msg,FILE_APPEND);
switch ($errno)
{
case E_NOTICE:return ;
case E_DEPRECATED:return;
}
throw $exception;
}
function getErrTypeName($errno)
{
switch ($errno)
{
case E_NOTICE:return 'E_NOTICE' ;
case E_DEPRECATED:return 'E_DEPRECATED';
default:return $errno;
}
}
function exceptionHandler($ex)
{
$msg = strval(date("Y-m-d h:i:s")).'=>'.getMsg($ex);
file_put_contents('./log/'.date("Ymd").'exception.txt',$msg,FILE_APPEND);
} www.jbxue.com
function getMsg($exception)
{
//获取最准确的异常 
while($exception->getPrevious())$exception = $exception->getPrevious();
$msg = ' Message: '.$exception->getMessage();
$msg .= ' File: '.$exception->getFile().':'.$exception->getLine()."\n";
return $msg;
}
set_error_handler('errorHandler',E_ALL);
set_exception_handler('exceptionHandler');
}
?>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值