Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

set_error_handler

Sets a custom function to handle PHP warnings and notices.

Syntax

set_error_handler(?callable $callback, int $error_levels = E_ALL): ?callable

Parameters

ParameterTypeDescription
$callback?callableA function that receives the error level, the message, the file and the line.
$error_levelsintOptional. 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 $undefined

Notes

Fatal errors are not caught by this handler. Uncaught exceptions are handled by set_exception_handler().

See also

  • error_log — Writes a message to the error log.
  • Exception — The base class of exceptions.

In the tutorial

  • Errors and debugging — The kinds of PHP errors, error display settings, the log, turning warnings into exceptions and debugging techniques.

Thanks for reading!

Donate to the site — we work hard for you.