9

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?

3
  • Try to read from the error_log file and write it in the database. Commented Feb 23, 2013 at 3:49
  • You should take a look at this if you want it saved to a variable: us3.php.net/manual/en/reserved.variables.phperrormsg.php Commented Feb 23, 2013 at 3:50
  • You can't catch parse errors, unless they're in a script that you include or require. Commented Feb 23, 2013 at 3:57

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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()).

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.