Jeff
Jeff

Reputation: 1162

Best practice for returning "error" from a function

I have a function:

public function CustomerRating() {
     $result = $db->query("...");
     $row = $result->fetch_assoc();

     if($row)
          $output = $row['somefield'];
     } else {
          $output = "error";
     }

     return $output;
}

//somewhere on another page...
if(is_numeric($class->CustomerRating()) {
     echo $class->CustomerRating;
} else {
      echo "There is an error with this rating.";
}

Is there a better way to find errors? In this function, if no rows are returned, it doesn't mean an "error" per se, it simply means the value can't be calculated. When I check for the result of a function, I feel like there is a better way to check the data being returned before I display it in the if function. What's the best way to do this? I'd like to return a "false", but how would I check for that when calling the function? Thanks!

Upvotes: 25

Views: 36251

Answers (7)

ssynhtn
ssynhtn

Reputation: 1377

Although returning false to indicate an error is prevalent in PHP libraries, there are several drawbacks:

  1. you can not return a description about the error
  2. if the false value is a valid return value of the function, then you can not use this approach

Another approach I see in my job is to return an array with both the normal result and the possible error, basically returning a pair, but then to get the real result you have to retrieve it from the array which is more unpleasant code to write

Exceptions are a full fledged solution to this problem but it's a bit cumbersome to write the try...catch block for simple errors. For a function that's documented to throw an exception, if you don't catch the exception when you call it, PhpStorm will complain about that, so in my opinion exceptions are better reserved for more severe errors

One way to return both the result and a possible error is to use a pass by reference parameter, which is used a lot in Objective C

/**
 * get element from array
  * @param $index int
  * @param $list array
  * @param $error object
  */
function getFromArray($index, $list, &$error=null) {
    if ($index >= 0 && $index < count($list)) {
        return $list[$index];
    }

    $error = "out of index";
    return null;
}

$list = ['hello', 'world'];

$error = null;
$result = getFromArray(-1, $list, $error);
if ($error) {
    echo "an error occurred " . $error;
} else {
    echo $result;
}

if you don't care about the error, you can just call the function leaving out the error parameter

echo getFromArray(0, $list);

Upvotes: 3

Sergey Eremin
Sergey Eremin

Reputation: 11080

You need exceptions:

public function CustomerRating() {
     $result = $db->query("...");
     $row = $result->fetch_assoc();
     if ($row !== null) {
          return $row['somefield'];
     } else {
          throw new Exception('There is an error with this rating.');
     }
}

// Somewhere on another page...
try {
    echo $class->CustomerRating();
} catch (Exception $e) {
    echo $e->getMessage();
}

Upvotes: 5

NeoNexus DeMortis
NeoNexus DeMortis

Reputation: 1326

Try this out:

public function CustomerRating() {
     $result = $db->query("...");
     $row = $result->fetch_assoc();

     if($row){
         $output = $row['somefield'];
     } else {
         $output = false;
     }

     return $output;
}

//somewhere on another page...
if($class->CustomerRating() !== false) {
     echo $class->CustomerRating();
} else {
     echo "There is an error with this rating.";
}

This will make sure that it won't break if you return a zero.

Upvotes: 0

Florent
Florent

Reputation: 12420

There are (in my opinion) 2 common ways:

  1. Returning false
    Many builtin PHP functions do that

  2. Using SPL exceptions
    Evolved PHP frameworks (Symfony2, ZF2, ...) do that

Upvotes: 14

Ray
Ray

Reputation: 41428

Use exceptions. Avoid returning errors from functions and methods

Upvotes: 3

rootman
rootman

Reputation: 670

the best way to deal with errors is to throw an exception. that way you can have all kinds of different errors and handle them accordingly.

you can then just do:

try {
    $myvar = CustomerRating();
    //do something with it
} catch (Exception $e) {
    echo $e->getMessage();
}

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 59997

I would use exceptions - Saves on the confusion.

Upvotes: 0

Related Questions