400 likes | 519 Views
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
E N D
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
Parse Error 11 <?php 12 for ($count = 10; $count >= 0; --$count) 13 if ($count == 0) 14 echo "<p>We have liftoff!</p>"; 15 else 16 echo "<p>Liftoff in $count seconds.</p>"; 17 } 18 ?> PHP Programming
Parse Error PHP Programming
Run-Time 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
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
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
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
Warnings PHP Programming
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
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
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
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
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
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.phphttp://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 fourarguments • 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.. • error code • error message • file where error occurred • 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.phphttp://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
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
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
Stub Functions function calcTax($amount) { return 1; } function isValid($email) { return true; } • "Stubs" are empty functions that serve as placeholders for a program’s actual functions • 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
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
Analyze Logic Isolate problematic code $n = 1; while($n < 10){ echo $n; } • for ($count = 1; $count < 6; $count++); • echo “$count<br/>”; PHP Programming
Learn More • http://www.w3schools.com/php/php_error.asp