set_error_handler
Sets a custom function to handle PHP warnings and notices.
Syntax
set_error_handler(?callable $callback, int $error_levels = E_ALL): ?callableParameters
| Parameter | Type | Description |
|---|---|---|
| $callback | ?callable | A function that receives the error level, the message, the file and the line. |
| $error_levels | int | Optional. Which error levels to handle. |
Return value
?callableThe previous handler, or `null`.
Examples
Turning a warning into an exception:
<?php
set_error_handler(function (int $level, string $message) {
throw new ErrorException($message);
});
try {
echo $undefined;
} catch (ErrorException $error) {
echo 'Caught: ', $error->getMessage();
}Output:
Caught: Undefined variable $undefinedNotes
Fatal errors are not caught by this handler. Uncaught exceptions are handled by set_exception_handler().
See also
In the tutorial
- Errors and debugging — The kinds of PHP errors, error display settings, the log, turning warnings into exceptions and debugging techniques.