How to catch fatal Errors in PHP

In this tutorial we will see how to catch the fatal errors in PHP.Normally we skip the fatal errors like calling a function which doesn't exist in file.

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

We can now use it with register_shutdown_function to handle fatal error, log, redirect, html page, instead of the infamous white page.We will use register_shutdown_function function to catch the fatal errors.

Note :  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.

register_shutdown_function( "handle_fatal_error" );

function handle_fatal_error() {
  $errfile = "unknown file";
  $errstr  = "shutdown";
  $errno   = E_CORE_ERROR;
  $errline = 0;

  $error = error_get_last();

  if( $error !== NULL) {
    $errno   = $error["type"];
    $errfile = $error["file"];
    $errline = $error["line"];
    $errstr  = $error["message"];
 echo "file-".$error["file"]. " type ".$error["type"]. " line ".$error["line"]." message ".$error["message"];die;

//This function is undefined
echo myfunction();die;

It will handle the fatal error and you can pass the error in mail also.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...