From 7311da4b2249361b6e8f41a26bde5043984d81de Mon Sep 17 00:00:00 2001 From: Sebastian Meyer Date: Wed, 24 Jan 2024 22:44:31 +0100 Subject: [PATCH] Add error handler for exceptions --- composer.json | 3 +- src/ErrorHandlers/TriggerExceptionError.php | 56 +++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 src/ErrorHandlers/TriggerExceptionError.php diff --git a/composer.json b/composer.json index 5c61f53..ae2297a 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ "StrictList", "StrictQueue", "StrictStack", - "ThrowErrorException" + "ThrowErrorException", + "TriggerExceptionError" ], "homepage": "https://github.com/opencultureconsulting/php-basics", "readme": "README.md", diff --git a/src/ErrorHandlers/TriggerExceptionError.php b/src/ErrorHandlers/TriggerExceptionError.php new file mode 100644 index 0000000..62eda21 --- /dev/null +++ b/src/ErrorHandlers/TriggerExceptionError.php @@ -0,0 +1,56 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +declare(strict_types=1); + +namespace OCC\Basics\ErrorHandlers; + +use Throwable; + +/** + * Trigger errors for uncaught exceptions. + * + * Usage: set_exception_handler(new TriggerExceptionError()); + * + * @author Sebastian Meyer + * @package Basics\ErrorHandlers + */ +class TriggerExceptionError +{ + /** + * Convert an uncaught exception into an PHP error. + * + * @param Throwable $exception The exception + * + * @return void + */ + public function __invoke(Throwable $exception): void + { + $message = sprintf( + 'Uncaught Exception [%d] in file %s on line %d: %s', + $exception->getCode(), + $exception->getFile(), + $exception->getLine(), + $exception->getMessage() + ); + trigger_error($message, E_USER_ERROR); + } +}