php全局异常/错误处理

dafenqi
2023-08-08 / 0 评论 / 10 阅读 / 正在检测是否收录...

php全局异常/错误处理

php自有try{throw{}}catch{}异常/错误捕获系统,难以在生产环境中运用;生产环境中,我们一般要求,一旦出现异常/错误,php立刻结束脚本,向访客浏览器输出出错提示,并通过自定义函数向管理员发送消息

以下就是php生产环境中的异常/错误处理方法

工具/原料

方法/步骤
在php代码开头处,增加代码:set_error_handler ( 'customerror' );

这是php的常规错误捕获函数,一旦程序运行过程中出现常规错误,customerror()函数就会被调用;customerror()运行完毕,php程序继续运行,因此在customerror()函数中的最后一句,需要die(); 结束脚本

customerror()有5个参数,这些参数会由set_error_handler()自动提供

customerror()函数的具体书写形式:

function customerror($error_level,$error_message,$error_file,$error_line,$error_context) {

<--这里就是错误处理脚本-->

die();//终止脚本

}

用set_exception_handler ( 'customexception' );

捕获php运行过程中产生的第一个异常,因为该函数一旦捕获异常,就会停止执行脚本,因此只能捕获到第一个异常,捕获到异常后,会调用customexception()函数

customexception()有一个参数,由set_exception_handler()自动提供

customexception()函数的具体书写形式:

function customexception($exception) {

<--这里就是错误处理脚本-->

}

用register_shutdown_function('customend');

这个不是用来处理错误的,这是一个在php脚本结束时自动调用一个函数的函数,因此我们可以利用它捕获能导致php脚本停止运行的严重错误(这类错误是不能被set_error_handler ()捕获的)

一旦脚本停止运行,customend()函数就会被调用,在customend()函数中通过error_get_last()来判断脚本是正常结束还是发生严重错误而中断,如果是发生严重错误而中断,则运行错误处理程序

customend()函数没有参数

customend()函数的具体书写形式如下:

function customend(){

if(error_get_last()){

<--这里就是错误处理脚本-->

}

}

php全局异常/错误处理
END
注意事项
set_error_handler () 还有第二个可省略参数,来确定低于哪个级别的错误不会被拦截

0

Deprecated: strtolower(): Passing null to parameter #1 ($string) of type string is deprecated in /www/wwwroot/testblog.58heshihu.com/var/Widget/Archive.php on line 1032

评论 (0)

取消