Get Exception or Error Handler in PHP 8.5

Get Exception or Error Handler in PHP 8.5

PHP provides set_exception_handler and set_error_handler functions for defining custom exception and error handlers that are invoked when an exception is not caught within a try/catch block or an error occurs. Since PHP 8.5, we can use get_exception_handler and get_error_handler functions to retrieve the currently registered handlers, or null if none are registered.

<?php

set_exception_handler(function (Throwable $throwable): void {
    echo $throwable->getMessage().PHP_EOL;
});
set_error_handler(function (int $code, string $error, string $file, int $line): void {
    echo $code.' '.$error.' '.$file.' '.$line.PHP_EOL;
});

var_dump(get_exception_handler()); // object(Closure)#1 (4) { ... }
var_dump(get_error_handler()); // object(Closure)#2 (4) { ... }

The returned handler is the exact callable value that was passed to set_exception_handler or set_error_handler function.

Leave a Comment

Cancel reply

Your email address will not be published.