2

I am writing program in PHP with MYSQL database.I want to catch error and give user define error instead of system error.I am using try and catch to handle exceptions but fatal error is not caught by try and catch.I used set_exception_handler but it not work for me.Tell me how to catch fatal error?

3 Answers3

3

1) Simple

How do I catch a PHP Fatal Error

2) Catch All

Sets a user function (error_handler) to handle errors in a script.

http://php.net/manual/en/function.set-error-handler.php

http://php.net/manual/en/book.errorfunc.php

3) Read on https://barelysufficient.org/2011/03/catching-fatal-errors-in-php/

Community
  • 1
  • 1
internals-in
  • 4,798
  • 2
  • 21
  • 38
1

Fatal errors cannot be tracked directly through error_handler(). You need to use register_shutdown_function() to catch those errors.

Example:

<?php
/**
 * Checks for a fatal error, work around for set_error_handler not working on fatal errors.
 */
function check_for_fatal()
{
    $error = error_get_last();
    if ( $error["type"] == E_ERROR )
        log_error( $error["type"], $error["message"], $error["file"], $error["line"] );
}

register_shutdown_function( "check_for_fatal" );
?>
anupam
  • 756
  • 5
  • 11
0

This is a modified example from PHP Manual [Personally Tested & Works]. I haven't used the register_shutdown() here.

<?php

set_error_handler( "log_error" );
set_exception_handler( "log_exception" );
function log_error( $num, $str, $file, $line, $context = null )
{

    log_exception( new ErrorException( $str, 0, $num, $file, $line ) );
}

function log_exception( Exception $e )
{

echo "Some Error Occured. Please Try Later.";
exit();
}

require_once("texsss.php");// I am doing a FATAL Error here

OUTPUT :

Some Error Occured. Please Try Later.

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126