我在触发错误的类中有一个方法。
/**
* Get info
* @return string|FALSE Info
*/
public function getInfo()
{
if ($this->info) {
return $this->info;
}
trigger_error('Missing info', E_USER_WARNING);
return FALSE;
}
我不想在这里抛出异常,因为我真的想要/需要这段代码继续运行。在其他地方,我记录了这个错误,并且记录错误超出了此类的范围。
但是我该如何记录呢?作为异常(exception),我会使用:
/**
* @throws Exception
*/
是否有类似的错误?我真的希望其他开发人员能够轻松了解我的代码中发生了什么。
没有用于错误的 phpdoc 标记。
trigger_error()
返回 bool 值,因此您的方法不会返回或抛出任何东西。除非您的错误处理程序阻止,否则执行将恢复,因此使用 @return 或 @throws 会误用它们,并且可能会让阅读您的代码的任何人感到困惑。
我会使用不同的方法。
我会这样做:
/**
* Has info
*
* @return bool Whether info is available
*/
public function hasInfo()
{
return (bool) $this->info; // or use isset() or whatever you need
}
/**
* Get info
*
* @throws Exception
* @return string The info string
*/
public function getInfo()
{
if (! $this->hasInfo()) {
throw new Exception('Missing info');
}
return $this->info;
}
然后从您的其他代码,您可以:
if ($object->hasInfo()) {
$info = $object->getInfo();
} else {
// no info!
}
我还会在我的代码库的根目录中捕获异常:
try {
MyApp::run();
}
catch(Exception $e) {
// handle error, eg. display fatal error message
}