PHP Errors As Exceptions

Bookmark on del.icio.us

With the use of the set_error_handler() function, PHP runtime errors can be turned into exceptions with the use of a custom function to throw an exception when a runtime error occurs. The error level can be set to E_WARNING, E_ALL or any error level supported by set_error_handler.


<?php

/*** set error handler level to E_WARNING ***/
set_error_handler('custom_handler', E_WARNING);

/**
*
* @custom error function to throw exception
*
* @param int $errno The error number
*
* @param string $errmsg The error message
*
*/
function custom_handler($errno, $errmsg)
{
throw new
Exception('This Error Happened '.$errno.': '. $errmsg);
}

Example Usage


<?php

/*** example code ***/
try
{
/*** try to open a non-existant file ***/
fopen('does_not.exist');
}
catch (
Exception $e)
{
/*** show the error message ***/
echo $e->getMessage();
}

?>

  1. No comments yet.

  1. No trackbacks yet.