Error Handling
PHP has various functions to handle errors and logging them. You can define your own error handling rules and the way errors must be logged. PHP error handling functions are as follows:
debug_backtrace
method
It Generates a backtrace. It also returns an associative array and array keys are:
[function]
: Current function name[line]
: Current line number[file]
: Current file name[class]
: Current class name[object]
: Current object[type]
: Current call type[args]
: If inside a function, lists the functions arguments. If inside an included file, lists the included file names
// syntax
debug_backtrace(option, limit);
Undestanding syntax:
option
: Specifies a bitmask for
DEBUG_BACKTRACE_PROVIDE_OBJECT
,
DEBUG_BACKTRACE_IGNORE_ARGS
- Optional.
limit
: Limits the number of stack frames printed. - Optional.
<?php
function x() {
y();
}
function y() {
z();
}
function z(){
var_dump(debug_backtrace());
}
x();
?>
<!-- Output
array(3) {
[0]=> array(4) {
["file"]=> string(21) "/home/check.php"
["line"]=> int(6)
["function"]=> string(1) "z"
["args"]=>
array(0) { }
}
[1]=> array(4) {
["file"]=> string(21) "/home/check.php"
["line"]=> int(3)
["function"]=> string(1) "y"
["args"]=> array(0) { }
}
[2]=> array(4) {
["file"]=> string(21) "/home/check.php"
["line"]=> int(11)
["function"]=> string(1) "x"
["args"]=> array(0) { }
}
}
-->
debug_print_backtrace
method
It prints a PHP backtrace.
// syntax
debug_print_backtrace(option, limit);
Understanding syntax
option
: Specifies a bitmask for DEBUG_BACKTRACE_IGNORE_ARGS
. - Optional.
limit
: Limits the number of stack frames printed. - Optional.
Code example
<?php
function x() {
y();
}
function y() {
z();
}
function z(){
debug_print_backtrace();
}
x();
?>
<!--
Output
#0 z() called at [/home/check.php:6]
#1 y() called at [/home/check.php:3]
#2 x() called at [/home/check.php:11]
-->
error_clear_last
method
It clears the last error.
// syntax
error_get_last();
// This function has no parameters.
error_get_last
method
It returns an associative array containing the last error occurred.
Array keys are:
[type]
: Error type[message]
: Error message[file]
: File where the error occurred[line]
: Line where the error occurred
// syntax
error_get_last();
Code example
<?php
echo $var;
print_r(error_get_last());
?>
<!--
Output
Array (
[type] => 8
[message] => Undefined variable: var
[file] => /home/file/check.php
[line] => 6
)
-->
error_log
method
Sends an error message to the defined error handling routines e.g : log, file etc.
// syntax
error_log(msg, msg_type, destination, headers);
Understanding syntax
msg
: Specifies error message. Required.
msg_type
: Where to send error messages. Optional. Possible values are :
0 : Message is sent to PHP’s system logger. Default case.
1 : Message is sent to the email mentioned in the destination.
3 : Message is appended to the file in the destination.
4 : Message is sent to SAPI logging handler.
destination
: Destination of the error messages. Optional.
headers
: Used when msg_type
is set to 1. Specifies additional headers like from, Cc, and Bcc. Optional.
Code example
<?php
// Sends an error message to the server log
if(!mysqli_connect("localhost","user","pwd","db")) {
error_log("Connection Failed..!", 0);
}
?>
error_reporting
method
Specifies which errors are reported.
// syntax
error_reporting(level);
Understanding syntax
level
: Error report level of script. Optional.
Code example
<?php
error_reporting(0);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
?>
restore_error_handler
method
Restores the previous error handler.
// syntax
restore_error_handler();
This function has no parameters.
Code example
<?php
function customErrHandler($errno, $errstr, $errfile, $errline){
echo "<h5> Error:</h5> [$errno] $errstr <br>";
echo " Error on line $errline<br>";
}
set_error_handler("customErrHandler");
$var = 20;
if ($var > 10) {
trigger_error("A custom error has been triggered");
}
restore_error_handler();
if ($var > 10) {
trigger_error("A custom error has been triggered");
}
?>
<!--
Output
Error:
[1024] A custom error has been triggered
Error on line 15
-->
restore_exception_handler
method
Restores the previous exception handler.
// syntax
restore_exception_handler();
Code example
<?php
function userException_1($arg) {
echo "[" . __FUNCTION__ . "]" . $arg>getMessage();
}
function userException_2($arg) {
echo "[" . __FUNCTION__ . "]" . $arg>getMessage();
}
set_exception_handler("userException_1");
set_exception_handler("userException_2");
restore_exception_handler();
throw new Exception("First exception handler will trigger");
?>
<!--
Output
[userException_1]First exception handler will trigger
-->
set_error_handler
method
Sets a user-defined error handler function.
// syntax
set_error_handler(error_handler, E_ALL | E_STRICT);
Understanding syntax
error_handler
: Name of the function which will be called at errors. Required
E_ALL | E_STRICT
: Optional. Specifies on which error report level, user error will be thrown.
Code example
<?php
function customErrHandler($errno, $errstr, $errfile, $errline){
echo "<h5> Error:</h5> [$errno] $errstr <br>";
echo " Error on line $errline <br>";
}
set_error_handler("customErrHandler");
$var = 20;
if ($var > 10) {
trigger_error("A custom error has been triggered");
}
restore_error_handler();
if ($var > 10) {
trigger_error("A custom error has been triggered");
}
?>
<!--
Output
Error:
[1024] A custom error has been triggered
Error on line 15
-->
set_exception_handler
method
Sets a user-defined exception handler function.
// syntax
set_exception_handler(exception_handler);
Understanding syntax
exception_handler
: Name of the function which will be called on catching an uncaught exception.
Code example
<?php
function myhandler($exception_arg) {
echo "Exception: " , $exception_arg->getMessage(), "\n";
}
set_exception_handler('myhandler');
throw new Exception('Exception');
echo "Not Executed \n";
?>
trigger_error
method
Generates a user-level error or warning messages.
// syntax
trigger_error(error_message, error_type);
Understanding syntax
error_message
: Specifies error message for this error. It is limited to 1024 bytes only. Required
error_type
: Specifies error type for this error. Optional. Possible values are ;
E_USER_ERROR
E_USER_WARNING
E_USER_NOTICE
code example
<?php
if($divisor == 0) {
trigger_error("Divide by 0 Error", E_USER_ERROR);
}
?>
user_error
method
Alias of trigger_error method.
Some predefined error & logging constants
are
Value |
Constant |
Description |
1 |
E_ERROR |
Fatal run-time errors. Errors that cannot be recovered from. For example: memory allocation problem. Script execution is halted. |
2 |
E_WARNING |
Run-time warnings (non-fatal errors). Script execution is not halted. |
4 |
E_PARSE |
Compile-time parse errors. Errors should only be generated by the parser. |
8 |
E_NOTICE |
Run-time notices. Indicates something that could be an error, but could also be running of a script normally. |
16 |
E_CORE_ERROR |
Fatal errors occurring during PHP's initial startup. Like E_ERROR, except it is generated by the core of PHP. |
32 |
E_CORE_WARNING |
Non-fatal errors during PHP startup. Like E_WARNING, except it is generated by the core of PHP. |
64 |
E_COMPILE_ERROR |
Fatal compile-time errors. |
128 |
E_COMPILE_WARNING |
Non-fatal compile-time errors. |
256 |
E_USER_ERROR |
Fatal user-generated error. |
2048 |
E_STRICT |
Display suggestions or warnings if exists, in order to change code into standard and upgraded form. |
8192 |
E_DEPRECATED |
Run-time notices. Caution for deprecated methods |
16384 |
E_USER_DEPRECATED |
User-generated warning message through trigger_error(). This is like an E_DEPRECATED, |
32767 |
E_ALL |
Enable all PHP errors and warnings |