-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGlobalErrorHandler.php
More file actions
115 lines (91 loc) · 2.59 KB
/
GlobalErrorHandler.php
File metadata and controls
115 lines (91 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
declare(strict_types=1);
namespace Phenix\Runtime\ErrorHandling;
use ErrorException;
use Throwable;
use function in_array;
class GlobalErrorHandler
{
private const FATAL_ERRORS = [
E_ERROR,
E_PARSE,
E_CORE_ERROR,
E_COMPILE_ERROR,
];
private static bool $registered = false;
private static bool $active = false;
/**
* @var callable|null
*/
private static $previousExceptionHandler = null;
public static function register(): void
{
if (self::$active) {
return;
}
self::$active = true;
set_error_handler(self::handleError(...));
self::$previousExceptionHandler = set_exception_handler(self::handleException(...));
if (! self::$registered) {
register_shutdown_function(self::handleShutdown(...));
self::$registered = true;
}
}
public static function restore(): void
{
if (! self::$active) {
return;
}
restore_error_handler();
restore_exception_handler();
self::$previousExceptionHandler = null;
self::$active = false;
}
public static function handleError(int $severity, string $message, string $file, int $line): bool
{
if ((error_reporting() & $severity) === 0) {
return false;
}
$exception = new ErrorException($message, 0, $severity, $file, $line);
report($exception, [
'severity' => $severity,
'source' => 'php-error',
]);
throw $exception;
}
public static function handleException(Throwable $exception): void
{
report($exception, [
'source' => 'uncaught-exception',
]);
if (self::$previousExceptionHandler !== null) {
(self::$previousExceptionHandler)($exception);
}
}
public static function handleShutdown(): void
{
self::handleShutdownError(error_get_last());
}
/**
* @param array{type: int, message: string, file: string, line: int}|null $error
*/
public static function handleShutdownError(array|null $error): void
{
if (! self::$active) {
return;
}
if ($error === null || ! in_array($error['type'], self::FATAL_ERRORS, true)) {
return;
}
report(new ErrorException(
$error['message'],
0,
$error['type'],
$error['file'],
$error['line']
), [
'severity' => $error['type'],
'source' => 'fatal-error',
]);
}
}