我意识到这是一个很大的话题,但我希望了解一些关于处理错误的最佳实践方法的粗略想法,特别是在topic中(但也对超越语言细节的良好模式感兴趣)。让我们假设这些类和应用程序是大规模的。
我还意识到,最推荐的方法是使用PHP异常模型,我感兴趣的是了解下面的示例是如何转化成这样的。
编辑:我正在寻找的是关于如何最好地处理在验证例如表单数据时生成的错误(而不是方法如何被调用的错误)的想法,也许异常模型不是针对这个用例结束编辑的。
特别是考虑到并非所有错误都需要立即显示/使用(多个异常是否可以在同一方法中出现?),有些可能需要记录(这是另一个问题),有些可能只有在其他依赖关系为真(或为假)时才相关,有些可能只是警告,一些可能是关键的,还有一些可能是状态/通知。
我目前采取的办法是:
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焦油的人,
发布于 2012-10-11 09:12:06
这要看情况了。但是,“适当”的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);
}在任何情况下,只有当方法实际被错误调用,或者方法以致命的方式失败时,才应该抛出异常。
https://stackoverflow.com/questions/12835984
复制相似问题