Tuesday, 14 October 2025

Error handling in PHP

Errors

An error is a mistake in a program that may be caused by writing incorrect syntax or incorrect code. 

An error message is displayed in the browser 

The error message contains the filename along with the location, a message describing the error, and the line number at which the error has occurred.

Types of Errors

There are 12 unique error types, which can be grouped into 4 main categories:

  • Syntax Error or Parse Error
  • Informational (Notices)
  • Actionable (Warnings)
  • Fatal Errors

Syntax Error

It is also known as a Parse error.

These errors can occur due to common reasons like 

  • unclosed quotes, 
  • missing semicolon, 
  • extra or missing parentheses, 
  • or unclosed brackets and many more. 

While compiling the program, a syntax error can be caught by the compiler.

 It gives a parse error or syntax error message.

Syntax Error - Example

Example 1: Missing semicolon

<?php  
    /*---syntax error-------------------*/  
    echo "Alex: Hi! I'm Alex. </br>";  
    echo "Bob: I'm Bob. How are you?"  
    echo "Alex: I'm good! and you?";  
    echo "Bob: I'm also good";  
?>  
Parse error: syntax error, unexpected token "echo", expecting "," or ";" in C:\xampp\htdocs\Test\syntax.php on line 5


Fatal Errors

Something so terrible has happened during the execution of the script that further processing simply cannot continue.
It occurs when PHP cannot execute a critical operation, such as 
  • calling a non-existent function
  • including a missing file.
These stop the script execution immediately.

Fatal Error example

<?php
function add($x, $y) 
{
$sum = $x + $y;
echo "sum = " . $sum;
}
$x = 0;
$y = 20;
add($x, $y);
diff($x, $y);
?>
Fatal error: Uncaught Error: Call to undefined function diff() in C:\xampp\htdocs\Test\fatal.php:10 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Test\fatal.php on line 10

Actionable Errors (Warning Errors)

Non-fatal errors that allow the script to continue execution.
Example: Including a missing file or using an undefined variable.
Indicate that something clearly wrong has happened and that action should be taken.
e.g. file not present, database not available, missing function arguments, etc

Warning errors example

<?php
$x = "GeeksforGeeks";
include("gfg.php");
echo $x . " Computer science portal";
?>
Warning: include(gfg.php): Failed to open stream: No such file or directory in C:\xampp\htdocs\Test\warning.php on line 3

Informational(Notice) Errors

Same as a warning error.

Harmless problem that can be avoided through the use of explicit programming.

The warning error does not stop/prevent the execution of the program.
e.g. use of an undefined variable, defining a string without quotes, etc.

Notice errors example

<?php
$x = "Notice errors are deprecated";
echo $x;
echo $error;
?>
Warning: Undefined variable $error in C:\xampp\htdocs\Test\Notice.php on line 4

PHP Error Levels

There are 16 error levels in PHP. The 16 error levels are listed here:
  • E_ERROR: Fatal runtime errors.
  • E_WARNING: Runtime warnings (non-fatal errors).
  • E_PARSE: Compile-time parse errors.
  • E_NOTICE: Notices (non-critical runtime errors).
  • E_CORE_ERROR: Fatal errors during PHP's initial startup.
  • E_CORE_WARNING: Warnings during PHP's initial startup.
  • E_COMPILE_ERROR: Fatal compile-time errors.
  • E_COMPILE_WARNING: Compile-time warnings.
  • E_USER_ERROR: User-generated error messages.
  • E_USER_WARNING: User-generated warning messages.
  • E_USER_NOTICE: User-generated notice messages.
  • E_STRICT: Suggestions for improving code compatibility.
  • E_RECOVERABLE_ERROR: Catchable fatal errors.
  • E_DEPRECATED: Notices for deprecated code.
  • E_USER_DEPRECATED: User-generated deprecation warnings.
  • E_ALL: Represents all errors and warnings (except E_STRICT in older PHP versions).

Causing (Triggering) errors

It is possible to cause errors in PHP at any point in your script.
The trigger_error( ) function takes two parameters: 
  • the string output message to be printed out as the error 
  • and an optional second parameter of the type of error
trigger_error($msg,$type);
e.g.
if (!$db_conn) {
trigger_error(‘db conn failed’,E_USER_ERROR);
}

trigger_error( ) is better than just printing an error message and exiting the script
trigger_error( ) takes the form of PHP’s default errors
—it will automatically print out the filename and line number where the error occurred.
The second parameter affects how the script should react to the error. 
If the second parameter is not provided, the default is a user notice—a minor message that many people might not even see. 
However, any error type can be given as the second parameter, which can halt the execution of the script if the error is triggered.

Customising Error Handling

Generally, how PHP handles errors is defined by various constants in the installation (php.ini). 
1. Set error reporting settings
2. Suppressing Errors
3. Custom Error Handler

1. Set error reporting settings

error_reporting($level)
This function can be used to control which errors are displayed and which are simply ignored. 
The $level is an optional parameter 
The effect only lasts for the duration of the execution of your script. 

<?php
// Turn off all error reporting
error_reporting(0);


// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);


// Reporting E_NOTICE (to report uninitialized variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL ^ E_NOTICE);

// Report ALL PHP errors
error_reporting(E_ALL);
?> 

Note: Hiding errors is NOT a solution to a problem. 

2. Suppressing Errors

The special @ operator can be used to suppress function errors. 
Any error produced by the function is suppressed and not displayed by PHP, regardless of the error reporting setting

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any diagnostic error that might be generated by that expression will be suppressed.
<?php
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '" . error_get_last()['message'] . "'");
?>

Note: Error suppression is NOT a solution to a problem.
It can be useful to locally define your own error-handling mechanisms.
If you suppress any errors, you must check for them yourself elsewhere.

3. Custom Error Handler

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

A custom error handler is never passed E_PARSE, E_CORE_ERROR or E_COMPILE_ERROR errors as these are considered too dangerous.
Often used in conjunction with a ‘debug’ flag for a neat combination of debug and production code display..














 

No comments:

Post a Comment