Ignore PHP error while printing custom error message

So:

@fopen($file);

      

Ignores any errors and continues

fopen($file) or die("Unable to retrieve file");

      

Ignore the error, kill the program and print its own message

Is there an easy way to ignore errors from the function, print your own error message, and not kill the program?

0


a source to share


5 answers


Usually:

if (!($fp = @fopen($file))) echo "Unable to retrieve file";

      



or using your way (which discards the file descriptor):

@fopen($file) or printf("Unable to retrieve file");

      

+4


a source


Use exceptions:

try {
   fopen($file);
} catch(Exception $e) {
   /* whatever you want to do in case of an error */
}

      



More information at http://php.net/manual/language.exceptions.php

+4


a source


slosd won't work. fopen does not throw exceptions. You have to manually change it I will change my second equalizer and combine it with slosd :

try
{
    if (!$f = fopen(...)) throw new Exception('Error opening file!');
} 
catch (Exception $e)
{
    echo $e->getMessage() . ' ' . $e->getFile() . ' at line ' . $e->getLine;
}
echo ' ... and the code continues ...';

      

+2


a source


Here is my own solution. Note that it requires either a global or a static variable of the script class, or a static one for easy reference. I wrote a class-style for him, but as long as he can find an array, he's fine.

class Controller {
  static $errors = array();
}

$handle = fopen($file) or array_push(Controller::errors,
  "File \"{$file}\" could not be opened.");

 // ...print the errors in your view

      

+1


a source


Instead of dying, you can throw an exception and do error handling centrally depending on which mode you see fit :-)

0


a source







All Articles