Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - How to catch an unexpected error?

Tags:

php

try-catch

I'm writing a script, where a lot of things could go wrong. I'm making if/else statements for the obvious things, that could heppen, but is there a way to catch something, that could possible heppen, but I don't know what it is yet?

For example something causes an error of some kind, in the middle of the script. I want to inform the user, that something has gone wrong, but without dozens of php warning scripts.

I would need something like

-- start listening && stop error reporting --

the script

-- end listening --

if(something went wrong)
$alert = 'Oops, something went wrong.';
else
$confirm = 'Everything is fine.'

Thanks.

like image 873
Mike Avatar asked Mar 21 '26 04:03

Mike


2 Answers

Why not try...catch?

$has_errors = false;    
try {
  // code here

} catch (exception $e) {    
  // handle exception, or save it for later
  $has_errors = true;
}

if ($has_errors!==false)
  print 'This did not work';

Edit:

Here is a sample for set_error_handler, which will take care of any error that happens outside the context of a try...catch block. This will also handle notices, if PHP is configured to show notices.

based on code from: http://php.net/manual/en/function.set-error-handler.php

set_error_handler('genericErrorHandler');

function genericErrorHandler($errno, $errstr, $errfile, $errline) {
    if (!(error_reporting() & $errno)) {
        // This error code is not included in error_reporting
        return;
    }

    switch ($errno) {
    case E_USER_ERROR:
        echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
        echo "  Fatal error on line $errline in file $errfile";
        echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
        echo "Aborting...<br />\n";
        exit(1);
        break;

    case E_USER_WARNING:
        echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
        break;

    case E_USER_NOTICE:
        echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
        break;

    default:
        echo "Unknown error type: [$errno] $errstr<br />\n";
        break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}
$v = 10 / 0 ;
die('here'); 
like image 169
Chris Baker Avatar answered Mar 22 '26 18:03

Chris Baker


Read up on Exceptions:

try {
   // a bunch of stuff
   // more stuff
   // some more stuff
} catch (Exception $e) {
   // something went wrong
}
like image 26
Alex Howansky Avatar answered Mar 22 '26 20:03

Alex Howansky