Debugging & Error handling

advertisement
CSCI 215
Web Programming II
Debugging &
Error Handling
Error Types

Parse (syntax) errors
◦ Occur when the scripting engine fails to
recognize code
◦ Example: Incorrectly spelled or mistyped words

Run-time errors
◦ Occur when the engine encounters a problem
while program is running
◦ Example: Division by zero

Logic errors
◦ Flaws in program design that prevent the
program from running as intended
◦ Example: Infinite loop
2
Parse Error
11
12
13
14
15
16
17
18
<?php
for ($count = 10; $count >= 0; --$count)
if ($count == 0)
echo "<p>We have liftoff!</p>";
else
echo "<p>Liftoff in $count seconds.</p>";
}
?>
PHP Programming
3
Parse Error
PHP Programming
4
Run-Time Errors
E_NOTICE
Indicate that the script encountered something that could
indicate an error, but could also happen in the normal
course of running a script.
E_USER_NOTICE
User-generated notice message, generated by
trigger_error().
E_WARNING
Run-time warnings (non-fatal errors). Execution of the script
is not halted.
E_USER_WARNING
User-generated warning message, generated by
trigger_error().
E_COMPILE_WARNING
Fatal compile-time errors.
E_CORE_WARNING
Warnings that occur during PHP's initial startup.
E_ERROR
Fatal run-time errors. These indicate errors that can not be
recovered from, such as a memory allocation problem.
Execution of the script is halted.
E_USER_ERROR
User-generated error message, generated by trigger_error().
E_COMPILE_ERROR
Fatal compile-time errors.
E_CORE_ERROR
Fatal errors that occur during PHP's initial startup.
E_PARSE
Compile-time parse (syntax) errors.
notices
warnings
fatal
errors
Notices
Raised for potential run-time errors that
do not prevent a script from executing
 Examples

◦ use of an undefined variable
◦ defining a string without quotes
PHP Programming
6
Notices
<?php
error_reporting(E_ALL);
echo '<p>Error 1: Undefined variable:</p>';
echo $undefined_var;
echo '<p>Error 2: Unquoted string:</p>';
$some_var = tryetrhrtdf;
?>
http://ned.highline.edu/~tostrander/215/error_handling/error1.php
Notices
Warnings
Do not prevent a script from executing
 Indicate that something clearly wrong has
happened and action should be taken.
 Examples:

◦ File not found
◦ Database not available
◦ Missing function arguments
PHP Programming
9
Warnings
function beginCountdown($time)
{
if (!isset($time))
$time = 10;
for ($count = $time; $count >= 0; —$count) {
if ($count == 0)
echo '<p>We have liftoff!</p>';
else
echo "<p>Liftoff in $count
seconds.</p>";
}
}
beginCountdown();
PHP Programming
10
Warnings
PHP Programming
11
Warnings
<?
echo '<p>Error 1: file not available:</p>';
$fp = fopen('file_does_not_exist.dat','r');
echo '<p>Error 2: db not available:</p>';
$results = mysql_query('SOME QUERY');
?>
http://ned.highline.edu/~tostrander/215/error_handling/error2.php
Warnings
Fatal Errors
Raised when a run-time error prevents a
script from executing
 Something so terrible has happened
during execution of your script that
processing cannot continue.
 Examples:

◦ Parse error
◦ Calling an undefined function
PHP Programming
14
Fatal Errors
<?
error_reporting(E_ALL);
echo '<p>Error 1: Undefined function:</p>';
$fp = non_existing_function('an_arg');
echo 'Code never gets here!!!';
?>
http://ned.highline.edu/~tostrander/215/error_handling/error3.php
Raising Errors

It is possible to force a PHP error at any
point in your script.
trigger_error($msg, $type);

Example:
if (!$name) {
trigger_error('No name entered',
E_USER_ERROR);
}
…
trigger_error()

trigger_error() accepts two arguments:
◦ A custom error message
◦ The error reporting level
 E_USER_ERROR
 E_USER_WARNING
 E_USER_NOTICE
PHP Programming
17
if (isset($_GET['height']) &&
isset($_GET['weight'])) {
if (!is_numeric($_GET['weight'])
|| !is_numeric($_GET['height'])) {
trigger_error(“User did not enter numeric
values”, E_USER_ERROR);
}
} else {
trigger_error(“Values not entered”,
E_USER_ERROR);
}
$bodyMass = $_GET['weight'] / ($_GET['height']
* $_GET['height']) * 703;
print "Your body mass index is $bodyMass";
PHP Programming
18
PHP Programming
19
php.ini Directives

display_errors
◦ prints script error messages
◦ default value of “On”

error_reporting
◦ determines which types of error messages
PHP should generate
◦ by default, assigned a value of “E_ALL”
PHP Programming
20
Set Error Reporting Level
error_reporting($level)
 Used to control which errors are
displayed, and which are ignored.
 Only lasts for the duration of your script

ini_set('display_errors', 1);
// turn all error reporting ON
// error_reporting(E_ALL);
// Report all errors except E_NOTICE
// error_reporting(E_ALL ^ E_NOTICE);
// Turn off all error reporting
error_reporting(0);
// generate errors
echo '<p>Error 1: Use of an undefined variable.</p>';
echo $undefined_var;
echo '<p>Error 2: Use of an unquoted string.</p>';
$some_var = tryetrhrtdf;
echo '<p>Error 3: file not available:</p>';
$fp = fopen('this_file_does_not_exist.dat','r');
echo '<p>Error 4: db not available:</p>';
$results = mysql_query('SOME QUERY');
echo '<p>Error 5: call to undefined function:</p>';
$fp = non_existing_function('an_arg');
echo 'Code never gets here!!!';
http://ned.highline.edu/~tostrander/215/error_handling/error4.php
Hiding Errors
Hiding errors is NOT a solution
to a problem.
 It is useful, however, to hide any
errors produced on a live server.
 While developing and debugging
code, displaying all errors is highly
recommended!

Suppressing Errors
The special @ operator can be used to
suppress function errors
 Any error produced by the function is
suppressed regardless of the error
reporting setting.

$db = @mysql_connect($h,$u,$p);
if (!$db) {
trigger_error(‘blah’, E_USER_ERROR);
}
Suppressing Errors
Error suppression is NOT a solution to a
problem.
 It can be useful to locally define your own
error handling mechanisms.
 If you suppress
errors, you must
check for them
yourself
elsewhere.

Custom Error Handling
You can write your own function to
handle PHP errors however you want.
 The handler function should receive four
arguments
 The handler function should return true
to indicate it has handled the error
 Register the function in your script as the
error handler

Custom Error Handling
function err_handler(
$errcode, $errmsg, $file, $lineno) {
echo ‘An error has occurred!<br />’;
echo “file: $file<br />”;
echo “line: $lineno<br />”;
echo “Problem: $errmsg”;
return true;
}
The handler must have 4 inputs..
1. error code
2. error message
3. file where error occurred
4. line at which error occurred
Custom Error Handling

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 errors
◦ Example: register a custom handler just for user
triggered errors
set_error_handler(‘err_handler’,
E_USER_NOTICE | E_USER_WARNING |
E_USER_ERROR);
Custom Error Handler
A custom error handler is never passed
E_PARSE, E_CORE_ERROR or
E_COMPILE_ERROR errors
 These are considered too dangerous

function err_handler($errcode,$errmsg,$file,$lineno) {
echo 'An error has occurred!<br />';
echo "file: $file<br />";
echo "line: $lineno<br />";
echo "Problem: $errmsg<br />";
return true;
}
set_error_handler('err_handler');
// register handler
echo '<p>Error 1: Use of an undefined variable.</p>';
echo $undefined_var;
echo '<p>Error 2: Use of an unquoted string.</p>';
$some_var = tryetrhrtdf;
echo '<p>Error 3: file not available:</p>';
$fp = fopen('this_file_does_not_exist.dat','r');
echo '<p>Error 4: db not available:</p>';
$results = mysql_query('SOME QUERY');
echo '<p>Error 5: call to undefined function:</p>';
$fp = non_existing_function('an_arg');
echo 'Code never gets here!!!';
http://ned.highline.edu/~tostrander
/215/error_handling/error5.php
Other Tips
Trace errors
 Follow coding standards
 Write stub functions
 “Comment out” problematic lines
 Analyze logic carefully

PHP Programming
33
Trace Errors
Tracing is the examination of individual
statements in an executing program
 echo one of the most useful ways to trace
PHP code
 Use echo to display the contents of a
variable, an array, or the value returned
from a function

PHP Programming
34
function calculatePay() {
$PayRate = 15; $NumHours = 40;
$GrossPay = $PayRate * $NumHours;
echo “Gross Pay: $GrossPay<br />”;
$FederalTaxes = $GrossPay * .06794;
$StateTaxes = $GrossPay * .0476;
$SocialSecurity = $GrossPay * .062;
$Medicare = $GrossPay * .0145;
$NetPay = $GrossPay - $FederalTaxes;
echo “Net Pay 1: $NetPay<br />”;
$NetPay *= $StateTaxes;
echo “Net Pay 2: $NetPay<br />”;
$NetPay *= $SocialSecurity;
echo “Net Pay 3: $NetPay<br />”;
$NetPay *= $Medicare;
echo “Net Pay 4: $NetPay<br />”;
return number_format($NetPay, 2);
}
PHP Programming
35
Stub Functions
function calcTax($amount)
{
"Stubs" are empty functions
return 1;
that serve as placeholders for
}
a program’s actual functions
function isValid($email)
{
return true;
}
Stubs return a hard-coded value
Use Comments to Debug
$Amount = 100000;
$Percentage = .08;
printf(“The interest rate or a loan in the amount of
$%.2f is %s%%.<br />”, $Amount, $Percentage * 100);
$YearlyInterest = $Amount * $Percentage;
// printf(“The amount of interest for one year is
// $%.2f.<br />”, $YearlyInterest);
// $MonthlyInterest = $YearlyInterest / 12;
// printf(“The amount of interest for one month is
// $%.2f.<br />”, $MonthlyInterest);
// $DailyInterest = $YearlyInterest / 365;
// printf(“The amount of interest for one day is $%.2f.
// <br />”, $DailyInterest);
The cause of an error in a statement is often the
result of an error in a preceding statement
PHP Programming
37
Analyze Logic
Logic errors are the hardest to debug
 You must analyze each statement carefully

if (!isset($_GET['firstName']))
echo “You must enter your first name!”;
exit();
echo “Welcome to my Web site, ” .
$_GET['firstName'];
PHP Programming
38
Analyze Logic
$n = 1;
while($n < 10){
echo $n;
}
Isolate
problematic
code
for ($count = 1; $count < 6; $count++);
echo “$count<br />”;
PHP Programming
39
Learn More

http://www.w3schools.com/php/php_error.asp
Download