views:

291

answers:

5

So:

@fopen($file);

Ignores any errors and continues

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

Ignores error, kills program and prints a custom message

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

+3  A: 

Typically:

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

or using your way (which discards file handle):

@fopen($file) or printf("Unable to retrieve file");
porneL
+3  A: 

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

slosd
fopen doesn't raise Exceptions.
JPot
It does, once you add appropriate handler:http://us2.php.net/manual/en/class.errorexception.php
porneL
A: 

Instead of dying you could throw an exception and do the error handling centrally in whichever fashion you see fit :-)

n3rd
+2  A: 

slosd's way won't work. fopen doesn't throw an exception. You should thow it manually I will modify your second exaple and combine it with slosd's:

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 ...';
Jet
A: 

Here's my own solution. Note that it needs either a script-level global or a static variable of a class for easy reference. I wrote it class-style for reference, but so long as it can find the array it'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
The Wicked Flea