I want to get warning and error messages into php $variables so I save them to my database.
For example when there is any kind of error, warning or similar:
Parse error: syntax error, unexpected T_VARIABLE in /example.php(136) on line 9
Warning: [...]
I want to get them to variable $error_code
How is this done?
For the simple case of just logging them:
set_error_handler(function($errno, $errstr, $errfile, $errline) use ($db) {
// log in database using $db->query()
});
Instead of just logging them into your database (with the likelihood you will not look at them after a while), you can also let those warnings, notices, etc. generate an Exception:
function exception_error_handler($errno, $errstr, $errfile, $errline)
{
if (error_reporting()) { // skip errors that were muffled
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
}
set_error_handler("exception_error_handler");
Source: ErrorException
An exception will have more serious side effects, so you should have an exception handler in place to prevent the uncaught exception to cause a white page of death.
Look into set_error_handler()
Sets a user function (error_handler) to handle errors in a script.
This function can be used for defining your own way of handling errors
during runtime, for example in applications in which you need to do
cleanup of data/files when a critical error happens, or when you need
to trigger an error under certain conditions (using trigger_error()).
I'm using error_get_last(); until I find a better solution
$lastError = error_get_last();
echo $lastError ? "Error: ".$lastError["message"]." on line ".$lastError["line"] : "";
// Save to db
There is a variable called $php_errormsg which gets the previous error message. Check here for more info - http://php.net/manual/en/reserved.variables.phperrormsg.php
Related
TCPDF uses a lot the PHP # operator to suppress error.
As my application use a custom error handler, it still get these "suppressed" errors.
How can I make it ignore #-suppressed errors?
I thought of finding out if the error comes from TCPDF using the backtrace but the error may come from a line not using # operator.
Such a line looks like (l. 6882) for instance:
if (($imsize = #getimagesize($file)) === FALSE) {
I've asked Nicola Asuni (TCPDF creator) about this specific error and he said: "The code is working fine and the error has been suppressed on purpose".
I use PHP function set_error_handler to handle errors.
And the following: error_reporting(E_ALL); on PHP 5.4
Check for error_reporting() inside the error handler (you should read the PHP Documentation, it explains your concrete case there)
See the example (adapted from PHP DOCS):
function myErrorHandler($errno, $errstr, $errfile, $errline ) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting or was called with #
return;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler('myErrorHandler');
#strpos();
I can't manage the following: I have an error handler which catches all E_WARNINGS but I only want to handle some of the warnings all the other I want to ignore and pass them to the default PHP error handler (which also takes all the other error types except the E_WARNINGS).
Is this even possible? Look at my simple error handler:
set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
if($errfile != 'somefile_for_example.php') {
// I don't care about this error throw it somewhere else!
}
echo 'error in this file handles my custom error handler';
return true;
}, E_WARNING);
PHP documentation says at: http://php.net/manual/en/function.set-error-handler.php
It is important to remember that the standard PHP error handler is
completely bypassed for the error types specified by error_types
unless the callback function returns FALSE.
Maybe then this should work:
$old_error_handler = set_error_handler(
function($errno, $errstr, $errfile, $errline, $errcontext) {
if($errfile != 'somefile_for_example.php') {
return false;
}
echo 'error in this file handles my custom error handler';
return true;
}, E_WARNING);
-
[Edit] Another user (Philipp) commented that set_error_handler returns old handler, but only for another custom one, not for the default handler.
-
In any case, when programming error handlers, one must always be extra careful with programming errors, as they cannot be handled (maybe test the functions by themselves first).
There isn't an easy solution to do this, if you really want the error handler of php.
If you call set_error_handler, you get the current error handler as return value, but only, if set_error_handler was called already. An possible solution to avoid this is to restore the error handler(restore_error_handler) trigger your own error(trigger_error) and set your own error handler again. Caveat from this is, you lost the information about error line, file and context. In addition, you can only trigger user errors, which means, you have to map each error type to an user error type.
I would suggest, to handle all errors in your custom handler - there's no real benefit in such workarounds.
Hello I have a code like that :
try
{
// Here I call my external function
do_some_work()
}
catch(Exception $e){}
The question is: If the do_some_work() has a problem and produce an Error this try catch will hide the error?
There are two types of error in PHP. There are exceptions, and there are errors.
try..catch will handle exceptions, but it will not handle errors.
In order to catch PHP errors, you need to use the set_error_handler() function.
One way to simplify things mught be to get set_error_handler() to throw an exception when you encounter an error. You'd need to tread carefully if you do this, as it has the potential to cause all kinds of trouble, but it would be a way to get try..catch to work with all PHP's errors.
If do_some_work() throws an exception, it will be catched and ignored.
The try/catch construct has no effect on standard PHP errors, only on exceptions.
produce a Fatal Error
No, catch can not catch Fatal Errors. You can not even with an error handler.
If you want to catch all other errors, have a look for ErrorException and it's dedicated use with set_error_handler:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
I need a solution to catch all PHP fatal errors, exceptions, warnings, etc. and have a callback.
I want to display a friendly version of the error to the user and log that error.
I'm thinking about using a text file per day for logging error.
Any suggestion or PHP class (library)?
php method: set_error_handler might be what you are looking for.
More at: http://www.php.net/manual/en/function.set-error-handler.php
and at: http://php.net/manual/en/book.errorfunc.php
This makes almost all errors become catchable instance of ErrorException:
set_error_handler(function($errno, $errstr, $errfile, $errline ){
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
use it before of the code that can give errors, for instances at the very top of your php file or in a common header included
Limits: Severest errors (PHP engine, server, syntax) cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called compromise it.
But, if syntax is correct and server don't broke, these errors should not appear.
If needed, you could workaround it with the register_shutdown_function() and error_get_last()
As of PHP 8 the best way to catch any and all Exceptions is to catch the Throwable interface which "is the base interface for any object that can be thrown via a throw statement". So your code would look something like this.
try {
# code...
} catch (\Throwable $th) {
# code...
}
Try launch this web page, you should see "Message: Division by Zero".
// Set Error Handler
set_error_handler (
function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
);
// Trigger an exception in a try block
try {
$a = 3/0;
echo $a;
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
I quite like the error handling from the kohana framework. You'd have to do a bit of work to pull it out though.
http://kohanaframework.org/
It will allow you to do error logging to a file and email a recipient. It also enables you to redirect to your friendly error page.
I would like to make it so that my scripts can continue to run even if there's a CERTAIN fatal error. Right now I can get this fatal error: PHP Fatal error: Uncaught exception 'MongoConnectionException' with message blah blah.
How do we catch this specific error, log it, but allow the script to continue to run? Anyone has idea regarding this?
// run some code
try{
// run code that throws the exception
}
catch(MongoConnectionException $e)
{
error_log($e->getMessage());
// or other logging capabilities
}
// keep running script.
catch the exception!!!
http://php.net/manual/en/language.exceptions.php
More generally on this subject, a little caution is required, as standard PHP fatal errors are not automatically converted into exceptions, this modified a little from the manual should go some way to mitigate this.
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
try {
/* Trigger exception */
strpos();
}
catch (ErrorException $e) {
// deal with the error
}