How to catch a php error (E_WARNING or E_ERROR) ?

Card Puncher Data Processing

About

This howto shows you how to catch an php error.

The general procedure is to:

  • create a exception to throw when an error happens
  • replace the general error handling function with our own that throw an exception instead.
  • then catch this exception to get the original error/warning message.

Step by steps

Create a php error exception

Frist, you create your exception class that will be thrown when an php error occurs example: the below ExceptionPhpError exception si created to represent an php error. It takes over the error file and error line.

class ExceptionPhpError extends ExceptionCompile
{
    private string $errorFile;
    private int $errorLine;
    public function setErrorFile($errorFile): ExceptionPhpError { $this->errorFile = $errorFile; return $this; }
    public function setErrorLine($errorLine): ExceptionPhpError { $this->errorLine = $errorLine; return $this; }
    public function getErrorFile(): string {  return $this->errorFile;  }
    public function getErrorLine(): int { return $this->errorLine; }
}

Throw an exception when there is a php error

You can set your own handler function that gets as argument:

  • an error number
  • an error message
  • an error file
  • and the error line

In this function, we just throw the previous created exception.

Example:

  • The handler function that throws the previous exception exception
$errorHandler = function($errorNumber, $errorMessage, $errorFile, $errorLine) {
            // error was suppressed with the @-operator
            if (0 === error_reporting()) {
                return false;
            }
            throw (
                (new ExceptionPhpError($errorMessage, 0, $errorNumber ))
                ->setErrorFile($errorFile)
                ->setErrorLine($errorLine)
            );
}
set_error_handler($errorHandler);

Running php code that throws error in a try/catch block

In the last step, you just need to wrap the php code that may throw php error such as E_WARNING, E_ERROR in a try catch/block to catch the exception.

Example with fopen where at the end, we restore the system error handler with the restore_error_handler function.

try {
    $filePointer = fopen($dangerousUrl, 'r');
} catch (ExceptionPhpError $e) {
    $message = $e->getMessage();
    // ... do whatever with the warning message
} finally {
    // restore to the previous handler
    restore_error_handler();
}





Discover More
Php Error Level Enotice Not Set
Php - Error

This page is the standard error handling system of php known also as the error functions. This system: triggers error at a certain level that may be caught via a global callback function. ...



Share this page:
Follow us:
Task Runner