错误报告关闭和打开

php.ini 的 display_errors = on 或者 off

代码里 ini_set(‘display_errors’,1) 或者 0

错误报告级别

最佳实践

开发环境下打开错误报告。并且错误报告级别 e_all
正式环境一定要关闭错误报告

//显示所有的错误类型
error_reporting(e_all);

//显示所有的错误类型,除了notice 提示之外
error_reporting(e_all ^ e_notice);
error_reporting(e_all &~ e_notice);

//关闭所有的php错误报告
error_reporting(0);

//报告所有的错误类型
error_reporting(-1);

举例

try {
    //找不到文件
    throw new exception('找不到文件',1);
    //没有权限访问
    throw new exception('没有权限',2);
} catch (exception $e) {
    $errno =  $e -> getcode();

    if($errno == 1){
        echo $e -> getfile();
    }elseif($errno == 2){
        echo $e -> getline();
    }
}

文件异常类

class fileexception extends exception{
    public function fileinfo(){
        return $this->getmessage();
    }
}

try {
    print "open file";
    throw new fileexception('file does not exist');
} catch (exception $e) {
    print $e -> fileinfo();
}

捕获多个异常

class fileexception extends exception{}

//文件不存在的异常
class filenotexistexception extends fileexception{}
//文件权限异常 
class filepermissionexception extends fileexception{}

function filehandle(){
    //文件不存在
    throw new filenotexistexception('file does not exist');

    //文件权限异常
    throw new filepermissionexception('access denied');

    //其他异常
    throw new fileexception('other exception');
}
try {
    filehandle();
} catch (filenotexistexception $e) {
    echo $e -> getmessage();
}catch(filepermissionexception $e){
    echo $e -> getmessage();
}catch(fileexception $e){
    echo $e -> getmessage();
}

全局异常处理

<?php 
class fileexception extends exception{
    //文件不存在
    const file_not_exist = 1;
    //权限不够
    const file_permission = 2;
}

function filehandle(){
    //文件不存在
    throw new fileexception('filenotexist',fileexception::file_not_exist);

    //权限不够
    throw new fileexception('filepermission',fileexception::file_permission);
}
try {
    filehandle();
} catch (exception $e) {
    switch ($e -> getcode()) {
        case fileexception::file_not_exist:
            echo($e->getmessage());
            break;
        case fileexception::file_permission:
            echo ($e -> getmessage());
            break;
    }
}catch(exception $e){
    echo 'exception';
}
?>
------------------------------------------
<?php 
function defaultexceptionhandle($e){
    printf("uncaught exception:%s in file %s on line %d",$e->getmessage(),$e->getfile(),$e->getline());
}

set_exception_handler('defaultexceptionhandle');
throw new exception('tese......');
?>