2

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.

5 Answers 5

7

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'); 
Sign up to request clarification or add additional context in comments.

5 Comments

Tryed it and it doesn't work on "Notice warnings", or is it supposed not to?
Not supposed to. Generally, one would turn off notices on a production server. That said, you can also use set_error_handler in addition to catch anything that happens outside of try...catch. This would include notices if you do have them enabled (again, not recommended for a production environment). See PHP docs for more: php.net/manual/en/function.set-error-handler.php
Well, the notice pretty much ruined all the script, so I would really like to catch it, isnt't there a way? :]
Like Chris said, there is. Rewrite it to an Exception, catch it and handle it. Above all, try to fix the code so that it doesn't raise the notice (unless it's a runtime event, it should be possible)
Yeah, there is... set_error_handler. Updated answer to include some code, but it is taken pretty much verbatim from the PHP doc that I linked to. It will catch ANY error that PHP reports.
3

Read up on Exceptions:

try {
   // a bunch of stuff
   // more stuff
   // some more stuff
} catch (Exception $e) {
   // something went wrong
}

Comments

1
 throw new Exception('Division by zero.');    
try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

http://php.net/manual/en/language.exceptions.php

5 Comments

i copied the code from the link above and removed the irrelevant parts.
You removed most of the relevant parts. The Exception in your code is being thrown OUTSIDE of try block so how do you imagine it being caught? The inverse() function in your code is undefined, so it will raise a fatal error. Did you even try to run this code?
Dude, I am serious. The throw was some rows above within the definition of inverse() function, which is pretty much the entire point of this example.
maybe if its the first time u see PHP code. btw, he wrote try-catch so i guess he knows how to use throw, but now its syntax.
Who is 'he'? BEcause I can't see any sgn of try-catch in the OP's question. And it doesn't matter if I've seen PHP code before or not, the code in your answer is still invalid.
1

You should definitely use the try-catch syntax to catch any exception thrown by your script.
Additionally you can extend exceptions and implement new ones that fulfill your needs.This way, you can throw your own exceptions when you find any other kind of unexpected error (error for your script's logic).
A very short example explaining the use of extending exceptions :

 //your own exception class
 class limitExceededException extends Exception { ... }

 try{
 // your script here
 if($limit > 10)
     throw new limitExceededException();
 }catch(limitExceededException $e){//catching only your limit exceeded exception
     echo "limit exceeded! cause : ".$e->getMessage(); 
 }catch(Exception $e){//catching all other exceptions
     echo "unidentified exception : ".$e->getMessage(); 
 }

1 Comment

+1. Good example. For completness' sake: in case like this a built-in OutOfRangeException should be used.
0

Besides using try/catch, I think it's important to consider if you should catch an unexpected error. If it's unexpected then your code has no idea how to handle it and allowing the application to continue may produce bad data or other incorrect results. It may be better to just let it crash to an error page. I just recently had a problem where someone had added generic exception handlers to everything, and it hid the original location of the exception making the bug difficult to find.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.