05 - Error
05 - Error
• Indicate that something clearly wrong has happened and that action
should be taken.
error_reporting($level)
This function can be used to control which errors are displayed, and
which are simply ignored. The effect only lasts for the duration of the
execution of your script.
1. Set error reporting settings
<?php
// Turn off all error reporting
error_reporting(0);
$db = @mysqli_connect($h,$u,$p);
if (!$db) {
trigger_error(‘blah’,E_USER_ERROR);
}
2. Suppressing Errors
$db
$db == @mysqli_connect($h,$u,$p);
@mysql_connect($h,$u,$p);
if (!$db) {
trigger_error(blah.',E_USER_ERROR);
}
Attempt to connect to
database. Suppress error
notice if it fails..
Since error is suppressed, it
2. Suppressing Errors
must be handled gracefully
somewhere else..
$db = @mysql_connect($h,$u,$p);
if (!$db)
if (!$db) {{
trigger_error(‘blah’,E_USER_ERROR);
trigger_error(blah.',E_USER_ERROR);
}}
2. Suppressing Errors
• You can write your own function to handle PHP errors in any way you
want.
• You simply need to write a function with appropriate inputs, then
register it in your script as the error handler.
• The handler function should be able to receive 4 arguments, and
return true to indicate it has handled the error…
3. Custom Error Handler
function err_handler(
$errcode,$errmsg,$file,$lineno) {
function err_handler(
$errcode,$errmsg,$file,$lineno) {
$errcode,$errmsg,$file,$lineno) {
function err_handler(
$errcode,$errmsg,$file,$lineno) {
echo
echo ‘An
‘An error
error has
has occurred!<br
occurred!<br />’;
/>’;
echo
echo“file:
“file:$file<br
$file<br/>”;
/>”;
echo “line: $lineno<br />”;
echo “line: $lineno<br />”;
echo “Problem: $errmsg”;
echo “Problem: $errmsg”;
returnAny
true;
PHP statements can be
}
executed…
3. Custom Error Handler
function err_handler(
$errcode,$errmsg,$file,$lineno) {
Return true to let PHP know
echo ‘An error has occurred!<br />’;
that the custom error handler
echo “file: $file<br />”;
has handled the error
echo “line: $lineno<br />”;
OK.
echo “Problem: $errmsg”;
return true;
return true;
}
3. Custom Error Handler
• The function then needs to be registered as your custom error handler:
set_error_handler(‘err_handler’);
• You can ‘mask’ the custom error handler so it only receives certain types
of error. e.g. to register a custom handler just for user triggered errors:
set_error_handler(‘err_handler’,
E_USER_NOTICE | E_USER_WARNING |
E_USER_ERROR);
3. Custom Error Handler