gpt4 book ai didi

php - php中错误处理的正确方法

转载 作者:行者123 更新时间:2023-12-03 07:42:29 24 4
gpt4 key购买 nike

我意识到这是一个很大的话题,但我很欣赏一些关于处理错误的最佳实践方法的粗略想法,特别是在 OO PHP 中(但也对超越语言细节的良好模式感兴趣)。让我们假设这些类和应用程序是大规模的。

我也意识到最推荐的方法是使用 PHPs 异常模型,我很想知道下面的示例如何转化为这个模型。

编辑 :我正在寻找的是关于如何最好地处理验证表单数据时产生的错误的想法(不是方法被调用的错误),也许异常模型不适合这个用例 结束编辑

特别是考虑到并非所有错误都需要立即显示/使用(可以在同一个方法中抛出多个异常吗?),有些可能需要记录(我猜这是另一个问题),有些可能只有在其他依赖项是相关的真(或假),有些可能只是警告,有些可能很关键,有些可能是状态/通知。

我目前采用的方法大致如下:

class ClassName()
{
public MethodName( $data, &$errors )
{
$e = [];

// validate content and perform data handling
// any errors should be added to the array $e

if( empty( $e ) ) {
return $processed_data;
} else {
$errors = $e;
return false;
}
}
}

// and then calling:
$method_call = ClassName::MethodName( $data, $errors );

if( $method_call ) // do something with the data/display success message etc.
else // decide what to do with any errors

tar 人,

最佳答案

这真的取决于。不过,“正确”的 OO 方法是使用异常。已经内置了许多不同类型的异常(参见 http://www.php.net/manual/en/spl.exceptions.php),您可以定义自己的异常(参见 http://php.net/manual/en/language.exceptions.php)。

使用它们的方法可能与此类似

function foo($bar)
{
if(!is_string($bar))
throw new InvalidArgumentException("String argument expected");

if(strlen($bar) > 50)
throw new LengthException("String argument is too long!");
}

然后,在调用代码时,使用 try/catch,例如
try {
foo("hjsdkfjhkvbnsjd");
} catch(LengthException $ex) {
// Trim the string
} catch (InvalidArgumentException $ex) {
// Try to recover. Cast or trim or something
} catch (Exception $ex) {
// We hit an exception we're not explicitly handling.
// Gracefully exit
die($ex->Message);
}

在任何情况下,只有在方法实际上被错误调用或者方法以致命方式失败时才应该抛出异常。

关于php - php中错误处理的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12835984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com