Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for returning "error" from a function

Tags:

function

php

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!

like image 754
Jeff Avatar asked Jul 13 '12 16:07

Jeff


4 Answers

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

like image 89
Florent Avatar answered Sep 26 '22 23:09

Florent


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();
}
like image 37
Sergey Eremin Avatar answered Sep 27 '22 23:09

Sergey Eremin


Use exceptions. Avoid returning errors from functions and methods

like image 34
Ray Avatar answered Sep 29 '22 23:09

Ray


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);
like image 43
ssynhtn Avatar answered Sep 26 '22 23:09

ssynhtn