forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptions.php
More file actions
246 lines (203 loc) · 7.54 KB
/
Exceptions.php
File metadata and controls
246 lines (203 loc) · 7.54 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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Exceptions\HasExitCodeInterface;
use CodeIgniter\Exceptions\HTTPExceptionInterface;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Exceptions as ExceptionsConfig;
use ErrorException;
use Psr\Log\LogLevel;
use Throwable;
/**
* Exceptions manager
*
* @see \CodeIgniter\Debug\ExceptionsTest
*/
class Exceptions
{
use ResponseTrait;
/**
* Config for debug exceptions.
*
* @var ExceptionsConfig
*/
protected $config;
/**
* The request.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* The outgoing response.
*
* @var ResponseInterface
*/
protected $response;
private ?Throwable $exceptionCaughtByExceptionHandler = null;
public function __construct(ExceptionsConfig $config)
{
$this->config = $config;
}
/**
* Responsible for registering the error, exception and shutdown
* handling of our application.
*
* @return void
*/
public function initialize()
{
set_exception_handler($this->exceptionHandler(...));
set_error_handler($this->errorHandler(...));
register_shutdown_function($this->shutdownHandler(...));
}
/**
* The callback to be registered to `set_exception_handler()`.
*
* @return void
*/
public function exceptionHandler(Throwable $exception)
{
$this->exceptionCaughtByExceptionHandler = $exception;
[$statusCode, $exitCode] = $this->determineCodes($exception);
$this->request = service('request');
if ($this->config->log && ! in_array($statusCode, $this->config->ignoreCodes, true)) {
$uri = $this->request->getPath() === '' ? '/' : $this->request->getPath();
log_message('critical', "{exClass}: {message}\n{routeInfo}\nin {exFile} on line {exLine}.\n{trace}", [
'exClass' => $exception::class,
'message' => $exception->getMessage(),
'routeInfo' => sprintf('[Method: %s, Route: %s]', $this->request->getMethod(), $uri),
'exFile' => clean_path($exception->getFile()), // {file} refers to THIS file
'exLine' => $exception->getLine(), // {line} refers to THIS line
'trace' => render_backtrace($exception->getTrace()),
]);
// Get the first exception.
$firstException = $exception;
while (($prevException = $firstException->getPrevious()) instanceof Throwable) {
$firstException = $prevException;
log_message('critical', "[Caused by] {exClass}: {message}\nin {exFile} on line {exLine}.\n{trace}", [
'exClass' => $prevException::class,
'message' => $prevException->getMessage(),
'exFile' => clean_path($prevException->getFile()), // {file} refers to THIS file
'exLine' => $prevException->getLine(), // {line} refers to THIS line
'trace' => render_backtrace($prevException->getTrace()),
]);
}
}
$this->response = service('response');
$handler = $this->config->handler($statusCode, $exception);
$handler->handle($exception, $this->request, $this->response, $statusCode, $exitCode);
}
/**
* The callback to be registered to `set_error_handler()`.
*
* @return bool
*
* @throws ErrorException
*/
public function errorHandler(int $severity, string $message, ?string $file = null, ?int $line = null)
{
if ($this->isDeprecationError($severity)) {
if ($this->isSessionSidDeprecationError($message, $file, $line)) {
return true;
}
if (! $this->config->logDeprecations || (bool) env('CODEIGNITER_SCREAM_DEPRECATIONS')) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return $this->handleDeprecationError($message, $file, $line);
}
if ((error_reporting() & $severity) !== 0) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false; // return false to propagate the error to PHP standard error handler
}
/**
* Checks to see if any errors have happened during shutdown that
* need to be caught and handle them.
*
* @return void
*/
public function shutdownHandler()
{
$error = error_get_last();
if ($error === null) {
return;
}
['type' => $type, 'message' => $message, 'file' => $file, 'line' => $line] = $error;
if ($this->exceptionCaughtByExceptionHandler instanceof Throwable) {
$message .= "\n【Previous Exception】\n"
. $this->exceptionCaughtByExceptionHandler::class . "\n"
. $this->exceptionCaughtByExceptionHandler->getMessage() . "\n"
. $this->exceptionCaughtByExceptionHandler->getTraceAsString();
}
if (in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE], true)) {
$this->exceptionHandler(new ErrorException($message, 0, $type, $file, $line));
}
}
/**
* Handles session.sid_length and session.sid_bits_per_character deprecations in PHP 8.4.
*/
private function isSessionSidDeprecationError(string $message, ?string $file = null, ?int $line = null): bool
{
if (PHP_VERSION_ID >= 80400 && str_contains($message, 'session.sid_')) {
log_message(
LogLevel::WARNING,
'[DEPRECATED] {message} in {errFile} on line {errLine}.',
[
'message' => $message,
'errFile' => clean_path($file ?? ''),
'errLine' => $line ?? 0,
],
);
return true;
}
return false;
}
/**
* Determines the HTTP status code and the exit status code for this request.
*/
protected function determineCodes(Throwable $exception): array
{
$statusCode = 500;
$exitStatus = EXIT_ERROR;
if ($exception instanceof HTTPExceptionInterface) {
$statusCode = $exception->getCode();
}
if ($exception instanceof HasExitCodeInterface) {
$exitStatus = $exception->getExitCode();
}
return [$statusCode, $exitStatus];
}
private function isDeprecationError(int $error): bool
{
$deprecations = E_DEPRECATED | E_USER_DEPRECATED;
return ($error & $deprecations) !== 0;
}
private function handleDeprecationError(string $message, ?string $file = null, ?int $line = null): true
{
// Remove the trace of the error handler.
$trace = array_slice(debug_backtrace(), 2);
log_message(
$this->config->deprecationLogLevel,
"[DEPRECATED] {message} in {errFile} on line {errLine}.\n{trace}",
[
'message' => $message,
'errFile' => clean_path($file ?? ''),
'errLine' => $line ?? 0,
'trace' => render_backtrace($trace),
],
);
return true;
}
}