Subleak
Subleak

Reputation: 135

Ignoring PHP error, while still printing a custom error message

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?

Upvotes: 0

Views: 693

Answers (5)

Robert K
Robert K

Reputation: 30328

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

Upvotes: 1

Jet
Jet

Reputation: 1171

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 ...';

Upvotes: 2

n3rd
n3rd

Reputation: 6089

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

Upvotes: 0

slosd
slosd

Reputation: 3464

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

Upvotes: 4

Kornel
Kornel

Reputation: 100080

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");

Upvotes: 4

Related Questions