In this tutorial we will see how to catch the fatal errors in PHP. Normally we can’t cache FATAL Error because those are FATAL.
This will be useful when you want to show specific well formatted error page rather than PHP Error, when your program ends unexpectedly due to some fatal errors.
We will use [code]register_shutdown_function[/code] function to catch the fatal errors and format as we need.
Keep in mind that register_shutdown_function will gets executed after your script execution ends either it is successful or ends with any error.
So before performing any action in this function we need to check if really any fatal occurs or not. If occurs then we will show error page else it will continue to run as it is. So to get the details of the last error we will use [code]error_get_last()[/code] function.
Code
[cc lang=”php”]
function catch_fatal_error()
{
// Getting Last Error
$last_error = error_get_last();
// Check if Last error is of type FATAL
if(isset($last_error[‘type’]) && $last_error[‘type’]==E_ERROR)
{
// Fatal Error Occurs
// Do whatever you want for FATAL Errors
}
}
register_shutdown_function(‘catch_fatal_error’);
[/cc]
Actually Good point is highlighted that register_shutdown_function will be executed even if your script ends successfully or with error. So if you have set error logging then you must check for last error.
[…] source: http://localhost/xpertdev/2013/01/catch-fatal-errors-in-php/ […]
[…] Catch Fatal Errors in PHP — a short tutorial on how you can catch the Fatal Errors and arrange them properly. […]
hi Avinash,
can you please give any example , how this works…!!!
thanks,
Gaurish
Which portion you are not able to understand?