Error and Logging Functions in PHP: PART 2

Introduction

In this article I describe the PHP error and logging functions restore_error_handler, restore_exception_handler, set_error_handler and set_exception_handler. To learn some other error and logging functions, go to:

  1. Error and Logging Functions in PHP: PART 1

PHP restore_error_handler function

The PHP restore_error_handler function restores the previous error handler function and this function always returns true.

Syntax

restore_error_handler()

Example

An example of the
function is:

<?
php
function
customError($errno, $errstr, $errfile, $errline)
{

echo
"<b>Custom error:</b> [$errno] $errstr<br />";
echo
" Error on line $errline in $errfile<br />";
}

set_error_handler
("customError");
 
$test
=2;

if
($test>1)
{
trigger_error("A custom error has been triggered");
}
restore_error_handler();
if ($test>1)
{
trigger_error("A custom error has been triggered");
}
?>


Output

restore-error-handler-in-php.gif

PHP restore_exception_handler function

The PHP restore_exception handler function restores the previous exception handler and it is always returns true.


Syntax

restore_exception_handler()

Example

An example of the
function is:

<?php

restore_exception_handler();

throw new Exception('Exception occured');

?>


Output

restore-exception-handler-in-php.gif 

PHP set_error_handler function

The PHP set_error_handler function sets a user-defined error handler function and it returns a string containing the previously defined error handler (if any).


Syntax

set_error_handler(errorFunction, errorType)

Parameter in set_error_handler function

The parameters of the function are:

Parameter Description
errorFunction It specifies the function to be run upon errors.
errorType It specifies which error report levels the user-defined error will be shown.

Example

An example of the
function is:

<?php
function
on_error($num, $str, $file, $line)
{

print
"Encountered error $num in $file, line $line: $str";
}

set_error_handler
("on_error");
print
$varname;
>


Output

set-error-handler-function-in-php.gif

PHP set_exception_handler function

The PHP set_exception_handler function sets a user-defined exception handler function and returns the name of the previously defined exception handler or null on error.


Syntax

set_exception_handler(exceptionFunction)

Parameter in set_exception_handler function

The parameter of the function is:

Parameter Description
exceptionFunction It specifies the function to be called when an uncaught exception occurs.

Example

An example of the
function is:

<?
php
function
GenrateException($exception)
{

echo
"Exception:" , $exception->getMessage();
}
set_exception_handler('GenrateException');
throw new Exception('Uncaught Exception occurred');
?>

 
Output

set-exception-handler-function-in-php.gif

Up Next
    Ebook Download
    View all
    Learn
    View all