Скажем, у меня есть класс с таким способом:
/*
*
* 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
может генерировать InvalidArgumentException
/RuntimeException
/PDOException
по причинам XYZ. Что мне делать? А что нет?
Номер 1
Добавьте все возможные исключения, которые могут бросать someFunction
в php-docs.
/*
*
* 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
Не делай ничего.