php的錯誤處理方法可以通過以下方式重寫(在代碼開始的地方自定義即可):
error_reporting(0);//0爲不輸出PHP自帶的錯誤輸出,E_ALL爲所有的警告和錯誤都輸出
set_error_handler([__CLASS__, 'appError']);
set_exception_handler([__CLASS__, 'appException']);
register_shutdown_function([__CLASS__, 'appShutdown']);
CLASS就是當前類了(當然也可以寫別的類),然後依次介紹下面的三個異常處理方法:
set_error_handler
字面意思就是自定義錯誤處理,也就是程序錯誤會使用這裏自定義的錯誤處理方法,示例如下:
/**
* Error Handler
* @param integer $errno 錯誤編號
* @param integer $errstr 詳細錯誤信息
* @param string $errfile 出錯的文件
* @param integer $errline 出錯行號
* @param array $errcontext
*/
public static function appError($errno, $errstr, $errfile = '', $errline = 0, $errcontext = [])
{
switch ($errno) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
ob_end_clean();
$errorStr = "$errstr ".$errfile." 第 $errline 行.";
self::halt($errorStr);
break;
default:
if(!empty(ob_get_contents())){
//清空緩存區
ob_end_clean();
}
$errorStr = "[$errno] $errstr ".$errfile." 第 $errline 行.";
require SUNNY_PATH."tpl/error.php";
exit;
break;
}
}
set_exception_handler
自定義的異常處理,示例如下
/**
* Exception Handler
* @param \Exception|\Throwable $e
*/
public static function appException($e)
{
if (!$e instanceof \Exception) {
$e = new \Exception($e);
}
if (IS_CLI) {
echo $e->getMessage().PHP_EOL;die;
} else {
if(!empty(ob_get_contents())){
//清空緩存區
ob_end_clean();
}
$errorStr = $e->getMessage();
require SUNNY_PATH."tpl/error.php";
exit;
}
}
register_shutdown_function
程序中斷異常處理,示例如下:
/**
* Shutdown Handler
*/
public static function appShutdown()
{
if ($e = error_get_last()) {
switch($e['type']){
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
self::halt($e);
break;
}
}
}
以上示例參考TP的錯誤處理,不過是參考的TP3