set_exception_handler
Sets a function for exceptions nobody caught.
Syntax
set_exception_handler(?callable $callback): ?callableParameters
| Parameter | Type | Description |
|---|---|---|
| $callback | ?callable | A function receiving a `Throwable` object. |
Return value
?callableThe previous handler, or `null`.
Examples
A common error page:
<?php
// index.php
set_exception_handler(function (Throwable $e) {
error_log($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
http_response_code(500);
echo 'Something went wrong. Please try again later.';
});
throw new RuntimeException('Database is unavailable');Notes
The program ends after the handler runs. Details go to the log, and the visitor sees a general phrase.
See also
- set_error_handler — Sets a custom function to handle PHP warnings and notices.
- Throwable — The common interface of everything that can be thrown and caught.
- error_log — Writes a message to the error log.
In the tutorial
- Errors and debugging — The kinds of PHP errors, error display settings, the log, turning warnings into exceptions and debugging techniques.