This howto shows you how to catch an php error.
The general procedure is to:
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; }
}
You can set your own handler function that gets as argument:
In this function, we just throw the previous created exception.
Example:
$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);
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();
}