-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathErrorHandler.php
More file actions
255 lines (219 loc) · 7.57 KB
/
ErrorHandler.php
File metadata and controls
255 lines (219 loc) · 7.57 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
<?php
declare(strict_types=1);
namespace Yiisoft\ErrorHandler;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Throwable;
use Yiisoft\ErrorHandler\Event\ApplicationError;
use Yiisoft\ErrorHandler\Exception\ErrorException;
use Yiisoft\Http\Status;
use function error_get_last;
use function error_reporting;
use function function_exists;
use function http_response_code;
use function ini_set;
use function register_shutdown_function;
use function set_error_handler;
use function set_exception_handler;
use function str_repeat;
use const DEBUG_BACKTRACE_IGNORE_ARGS;
use const PHP_SAPI;
/**
* `ErrorHandler` handles out of memory errors, fatals, warnings, notices and exceptions.
*/
final class ErrorHandler
{
/**
* @var int The size of the reserved memory. A portion of memory is pre-allocated so that
* when an out-of-memory issue occurs, the error handler is able to handle the error with
* the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
* Defaults to 256KB.
*/
private int $memoryReserveSize = 262_144;
private string $memoryReserve = '';
private bool $debug = false;
private ?string $workingDirectory = null;
private bool $enabled = false;
private bool $initialized = false;
/**
* @param LoggerInterface $logger Logger to write errors to.
* @param ThrowableRendererInterface $defaultRenderer Default throwable renderer.
* @param EventDispatcherInterface|null $eventDispatcher Event dispatcher for error events.
* @param int $exitShutdownHandlerDepth Depth of the exit() shutdown handler to ensure it's executed last.
*/
public function __construct(
private readonly LoggerInterface $logger,
private readonly ThrowableRendererInterface $defaultRenderer,
private readonly ?EventDispatcherInterface $eventDispatcher = null,
private readonly int $exitShutdownHandlerDepth = 2,
) {}
/**
* Handles throwable and returns error data.
*
* @param ThrowableRendererInterface|null $renderer
* @param ServerRequestInterface|null $request
*/
public function handle(
Throwable $t,
?ThrowableRendererInterface $renderer = null,
?ServerRequestInterface $request = null,
): ErrorData {
$renderer ??= $this->defaultRenderer;
try {
$this->logger->error($t->getMessage(), ['throwable' => $t]);
return $this->debug ? $renderer->renderVerbose($t, $request) : $renderer->render($t, $request);
} catch (Throwable $t) {
return new ErrorData((string) $t);
}
}
/**
* Enables and disables debug mode.
*
* Ensure that is is disabled in production environment since debug mode exposes sensitive details.
*
* @param bool $enable Enable/disable debugging mode.
*/
public function debug(bool $enable = true): void
{
$this->debug = $enable;
}
/**
* Sets the size of the reserved memory.
*
* @param int $size The size of the reserved memory.
*
* @see $memoryReserveSize
*/
public function memoryReserveSize(int $size): void
{
$this->memoryReserveSize = $size;
}
/**
* Register PHP exception and error handlers and enable this error handler.
*/
public function register(): void
{
if ($this->enabled) {
return;
}
if ($this->memoryReserveSize > 0) {
$this->memoryReserve = str_repeat('x', $this->memoryReserveSize);
}
$this->initializeOnce();
// Handles throwable that isn't caught otherwise, echo output and exit.
set_exception_handler(function (Throwable $t): void {
if (!$this->enabled) {
return;
}
$this->renderThrowableAndTerminate($t);
});
// Handles PHP execution errors such as warnings and notices.
set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
if (!$this->enabled) {
return false;
}
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting.
return true;
}
$backtrace = debug_backtrace(0);
if (!isset($backtrace[0]['file'])) {
array_shift($backtrace);
}
array_shift($backtrace);
throw new ErrorException($message, $severity, $severity, $file, $line, null, $backtrace);
});
$this->enabled = true;
}
/**
* Disable this error handler.
*/
public function unregister(): void
{
if (!$this->enabled) {
return;
}
$this->memoryReserve = '';
$this->enabled = false;
}
private function initializeOnce(): void
{
if ($this->initialized) {
return;
}
// Disables the display of error.
if (function_exists('ini_set')) {
ini_set('display_errors', '0');
}
// Handles fatal error.
register_shutdown_function(function (): void {
if (!$this->enabled) {
return;
}
$this->memoryReserve = '';
$e = error_get_last();
if ($e !== null && ErrorException::isFatalError($e)) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$error = new ErrorException(
$e['message'],
$e['type'],
$e['type'],
$e['file'],
$e['line'],
null,
$backtrace,
);
$this->renderThrowableAndTerminate($error);
}
});
if (!(PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg')) {
/**
* @var string
*/
$this->workingDirectory = getcwd();
}
$this->initialized = true;
}
/**
* Renders the throwable and terminates the script.
*/
private function renderThrowableAndTerminate(Throwable $t): void
{
if (!empty($this->workingDirectory)) {
chdir($this->workingDirectory);
}
// Disable error capturing to avoid recursive errors while handling exceptions.
$this->unregister();
// Set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent.
http_response_code(Status::INTERNAL_SERVER_ERROR);
echo $this->handle($t);
$this->eventDispatcher?->dispatch(new ApplicationError($t));
$handler = $this->wrapShutdownHandler(
static function (): void {
exit(1);
},
$this->exitShutdownHandlerDepth,
);
register_shutdown_function($handler);
}
/**
* Wraps shutdown handler into another shutdown handler to ensure it is called last after all other shutdown
* functions, even those added to the end.
*
* @param callable $handler Shutdown handler to wrap.
* @param int $depth Wrapping depth.
* @return callable Wrapped handler.
*/
private function wrapShutdownHandler(callable $handler, int $depth): callable
{
$currentDepth = 0;
while ($currentDepth < $depth) {
$handler = static function () use ($handler): void {
register_shutdown_function($handler);
};
$currentDepth++;
}
return $handler;
}
}