php 从函数返回“错误”的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11474168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:35:40  来源:igfitidea点击:

Best practice for returning "error" from a function

phpfunction

提问by Jeff

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!

有没有更好的方法来查找错误?在这个函数中,如果没有返回任何行,它本身并不意味着“错误”,它只是意味着无法计算该值。当我检查函数的结果时,我觉得有一种更好的方法来检查返回的数据,然后再将其显示在 if 函数中。做到这一点的最佳方法是什么?我想返回一个“false”,但是在调用函数时如何检查它?谢谢!

采纳答案by Florent

There are (in my opinion) 2 common ways:

有(在我看来)两种常见的方式:

  1. Returningfalse
    Many builtin PHP functions do that

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

  1. 返回false
    许多内置的 PHP 函数都可以做到这一点

  2. 使用SPL 异常
    Evolved PHP frameworks (Symfony2, ZF2, ...) 做到这一点

回答by Ray

Use exceptions. Avoid returning errors from functions and methods

使用异常。避免从函数和方法返回错误

回答by Sergey Eremin

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();
}

回答by ssynhtn

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

尽管返回 false 来指示错误在 PHP 库中很普遍,但还是有几个缺点:

  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
  1. 你不能返回关于错误的描述
  2. 如果 false 值是函数的有效返回值,则不能使用此方法

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

异常是这个问题的完整解决方案,但是为简单的错误编写 try...catch 块有点麻烦。对于一个被记录为抛出异常的函数,如果你在调用它时没有捕捉到异常,PhpStorm 会抱怨,所以在我看来,异常最好保留用于更严重的错误

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

返回结果和可能的错误的一种方法是使用传递引用参数,它在目标 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);

回答by NeoNexus DeMortis

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.

如果您返回零,这将确保它不会中断。

回答by Ed Heal

I would use exceptions- Saves on the confusion.

我会使用例外- 节省混乱。

回答by rootman

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();
}