Skip to content

Commit b84ba23

Browse files
committed
New FatalErrorHandler #11708
To be able to show `max_execution_time` errors to human
1 parent 04c6d91 commit b84ba23

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/FatalErrorHandler.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Ecodev\Felix;
6+
7+
final class FatalErrorHandler
8+
{
9+
/**
10+
* Transform some specific PHP fatal errors into HTTP 500 with a JSON response
11+
* containing the error message (only). So that the client might show the error to the end-user.
12+
*
13+
* This must be called exactly **ONE TIME**.
14+
*
15+
* This will only work if HTTP headers were not sent already. So in development,
16+
* where `error_reporting` is most likely enabled, it might not work.
17+
*/
18+
public static function register(): void
19+
{
20+
register_shutdown_function(function (): void {
21+
$message = error_get_last()['message'] ?? null;
22+
if (!headers_sent() && $message && str_starts_with($message, 'Maximum execution time of')) {
23+
header('content-type: application/json');
24+
http_response_code(500);
25+
26+
echo json_encode(['message' => $message], JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
27+
}
28+
});
29+
}
30+
}

0 commit comments

Comments
 (0)