PHP 注册错误和异常处理机制
介绍
全局捕捉异常错误,并记录到日志系统
代码
<?php
namespace lib;
use Exception;
class Error
{
protected static $exceptionHandler;
public static function register()
{
error_reporting(E_ALL);
set_error_handler([__CLASS__, 'error']);
set_exception_handler([__CLASS__, 'exception']);
register_shutdown_function([__CLASS__, 'shutdown']);
}
public static function exception($e)
{
self::report($e);
}
public function report(Exception $exception)
{
$data = [
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
];
\think\facade\Log::error('错误信息',$data);
}
public static function error($errno, $errstr, $errfile = '', $errline = 0): void
{
$data = [
'file' => $errfile,
'line' =>$errline,
'message' => $errstr,
'code' => $errno,
];
\think\facade\Log::error('错误信息',$data);
}
public static function shutdown()
{
if (!is_null($error = error_get_last()) && self::isFatal($error['type'])) {
self::error($error);
}
}
protected static function isFatal($type)
{
return in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE]);
}
}
在入口文件中调用进行注册
// 注册错误和异常处理机制
\lib\Error::register();




