programulin/errors-handler

此包的最新版本(1.1.0)没有可用的许可证信息。

1.1.0 2019-04-05 16:40 UTC

This package is not auto-updated.

Last update: 2024-09-29 07:58:28 UTC


README

使用函数 set_error_handler 来捕获错误

  • set_error_handler
  • set_exception_handler
  • register_shutdown_function

可以在 callback-函数中处理它们(记录日志、输出 HTML 模板等),该函数需要传递给 register 方法。

安装

composer require programulin/errors-handler

示例

基本使用

use Programulin\ErrorHandler\ErrorHandler;

$handler = new ErrorHandler();

$handler->register(function($message, $exception) {
	var_dump($message);
	var_dump($exception);
});

$message 包含错误文本,$exception 是异常(或 null),您可以从其中获取 trace。

其他方法

// Аналог ini_set('display_errors', 'off');
$handler->setDisplayErrors('off');

// Аналог error_reporting(E_ALL);
$handler->setErrorReporting(E_ALL);

// Перечисляем уровни ошибок, которые наш обработчик должен игнорировать
$handler->disallow([E_NOTICE, E_STRICT]);

// Превращает не фатальные ошибки в исключения
$handler->throwErrors(true);

简短版本

(new ErrorHandler())->register(function($message, $exception) {
	var_dump($message);
	var_dump($exception);
})
	->setDisplayErrors('off')
	->setErrorReporting(E_ALL)
	->disallow([E_STRICT])
	->throwErrors(true);

与 Monolog 库一起使用的示例

require 'vendor/autoload.php';

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Programulin\ErrorHandler\ErrorHandler;

$logger = new Logger('errors');
$logger->pushHandler(new StreamHandler('errors.log'));

(new ErrorHandler())->register(function($message, $exception) use ($logger) {
	$logger->error($message, [
		'exception' => $exception,
		'uri' => $_SERVER['REQUEST_URI']
	]);
})
	->setDisplayErrors('off')
	->setErrorReporting(E_ALL)
	->disallow([E_STRICT])
	->throwErrors(true);

特性

在安装时将 throwErrors 设置为 true,非致命错误将转换为异常(除了由 @ 抑制的,以及传递给 disallow 方法的级别)。这意味着在捕获错误后,脚本不会继续执行

(new ErrorHandler())->register(function($message){
	var_dump($message);
})->throwErrors(true);

// Поскольку $title не определена, эта строка вызовет ошибку E_NOTICE, которая превратится в исключение
echo $title;

// Эта строка кода уже не будет выполнена
echo 'test';

要继续执行脚本,可以使用 try-catch

(new ErrorHandler())->register(function($message){
	var_dump($message);
})->throwErrors(true);

try {
	echo $title;
} catch(\Exception $e) {
	echo 'Ошибка отловлена';
}

// Теперь эта строка будет выполнена
echo 'test';