【发布时间】:2013-03-13 07:46:51
【问题描述】:
假设我有一个类,其方法如下:
/*
*
* Loads the user from username.
*
* @param string $username The username
*
* @return UserInterface
*
* @throws userNotFoundException if the user is not found
*/
public function getUser($username)
{
// someFunction return an UserInterface class if found, or null if not.
$user = someFunction('SELECT ....', $username);
if ($user === null) {
throw new userNotFoundException();
}
return $user
}
现在假设 someFunction 可能会因为 XYZ 原因抛出 InvalidArgumentException / RuntimeException / PDOException。我该怎么办? 还有什么不呢?
1 号
在 php-docs 中添加所有可能引发 someFunction 的异常。
/*
*
* Loads the user from username.
*
* @param string $username The username
*
* @return UserInterface
*
* @throws userNotFoundException if the user is not found
* @throws InvalidArgumentException
* @throws ...
*/
2号
添加一个 try-catch 块以确保该方法应仅在文档中引发异常
/*
*
* Loads the user from username.
*
* @param string $username The username
*
* @return UserInterface
*
* @throws userNotFoundException if the user is not found
* @throws RuntimeException
*/
public function getUser($username)
{
try {
$user = someFunction('SELECT ....', $username);
} catch (Exception $e) {
throw new RuntimeException();
}
if ($user === null) {
throw new userNotFoundException();
}
return $user
}
3 号
什么都别做。
【问题讨论】:
-
Number1 和 Number2 在文档方面有什么区别?您是在询问文档或处理异常的最佳实践吗?