UncaughtExceptionLogger.php
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\Exceptions; |
| 4 | |
| 5 | use Error; |
| 6 | use Exception; |
| 7 | use Give\Framework\Exceptions\Contracts\LoggableException; |
| 8 | use Give\Framework\Exceptions\Traits\Loggable; |
| 9 | use Give\Log\Log; |
| 10 | |
| 11 | class UncaughtExceptionLogger { |
| 12 | /** |
| 13 | * @var callable|null |
| 14 | */ |
| 15 | private $previousHandler; |
| 16 | |
| 17 | /** |
| 18 | * Registers the class with the set_exception_handler to receive uncaught exceptions |
| 19 | * |
| 20 | * @since 2.11.1 |
| 21 | */ |
| 22 | public function setupExceptionHandler() { |
| 23 | if ( $this->previousHandler !== null ) { |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | $this->previousHandler = @set_exception_handler( [ $this, 'handleException' ] ); |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * Handles an uncaught exception by checking if the Exception is native to GiveWP and then logging it if it is |
| 32 | * |
| 33 | * @since 2.12.0 re-throw the exception so it displays |
| 34 | * @since 2.11.2 remove parameter typing as it may be an Error |
| 35 | * @since 2.11.1 |
| 36 | * |
| 37 | * @param Exception|Error $exception |
| 38 | * |
| 39 | * @throws LoggableException |
| 40 | */ |
| 41 | public function handleException( $exception ) { |
| 42 | if ( $exception instanceof LoggableException ) { |
| 43 | /** @var LoggableException|Loggable $exception */ |
| 44 | Log::error( $exception->getLogMessage(), $exception->getLogContext() ); |
| 45 | } |
| 46 | |
| 47 | if ( $this->previousHandler !== null ) { |
| 48 | $previousHandler = $this->previousHandler; |
| 49 | $previousHandler( $exception ); |
| 50 | } else { |
| 51 | throw $exception; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 |