最佳实践:在php-doc中使用@throws,以及如何处理它
假设我有一个类,其方法如下:
/*
*
* 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
}
现在让我们假设可以出于XYZ原因抛出/ / 。我该怎么办?什么不是?someFunction
InvalidArgumentException
RuntimeException
PDOException
第 1 步
添加所有可能在 php 文档中引发的异常。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 步
不要做任何事情。