While we run an web application some page may contain error and some page maynot contain error, I want to get a notification if the page contains some error ,If there is an error we can see the error in the page, but can 开发者_C百科we set any value to a variable if the page contains error.. such that we can get the notification that there is an error . I want to get the notification since i want to create an error log,If we can set the variable with some value then we can use some condition to create a logfile How can we do that?
There is several ways to do it. One is to setup a custom error handler. PHP will trap most errors raised during script execution and pass it to your custom handler then. What you do inside the handler is up to you. You can write to a log and then redirect to somewhere else or whatever you want.
If you are talking about Exceptions, then wrap code that can break in try/catch blocks. If an error occurs, handle the exception the catch block. What you put in there is again up to you.
Go through the linked pages to learn how this works. Catching an error, setting a variable and writing to a log are three distinct things. Isolate and solve them one by one.
You could also consider using a try { } catch { } block and writing exceptions to error log in catch { } part. Like this:
try {
$db = new MyDb('127.0.0.1', 'root', 'root');
if (false === $db) {
throw new Exception ('Could not connect to the database.');
}
$row = $db->getTable('table_name')->getRowByColumn('id', $_GET['id']);
if (null === $row) {
throw new Exception ('Row with id ' . $_GET['id'] . ' not found.')
}
// and so on
} catch (Exception $e) {
$fp = fopen('logs/error.txt', 'w');
fwrite($fp, date('l jS \of F Y h:i:s A') . ': ' . $e->getMessage() . "\n");
fclose($fp);
}
You get the idea.
Instead of just a date of error you could also append a login of signed in user if the script is in authentication protected area so you know which user got that error.
精彩评论