0

我搜索了很长时间(这里也是),阅读了很多php代码,但仍然找不到令人满意的答案。这似乎是一个太宽泛的话题,但它确实结合在一起——最后对我来说。能否请你帮忙?

在一个 php 网站中,我将 PDO 作为 DAL,BLL 对象使用什么,它们是从 UI 调用的。现在,如果发生了什么事,PDO 会抛出 PDOException。当然,UI 层不必知道任何关于 PDOExceptions 的信息,因此 BLL 对象会捕获它。但现在呢?

我读过

  1. 例外是针对真正特殊的情况和
  2. 一个从低层重新抛出异常,以免上层出现低级异常。

让我说明我的问题(请不要关注函数args):

class User
{
 function signUp()
 {
  try
  {
   //executes a PDO query
   //returns a code/flag/string hinting the status of the sign up:
   //success, username taken, etc.
  }
  catch (PDOException $e)
  {
   //take the appropriate measure, e.g. a rollback

   //DataAccessException gets all the information (e.g. message, stack
   //trace) of PDOException, and maybe adds some other information too
   //if not, it is like a "conversion" from PDOException to DAE
   throw new DataAccessException();
  }
 }
}

//and in an upper layer
$user = new User();
try
{
 $status = $user->signUp();
 //display a message regarding the outcome of the operation
 //if it was technically successful
}
catch (DataAccessException $e)
{
 //a technical problem occurred
 //log it, and display a friendly error message
 //no other exception is thrown
}

这是一个正确的解决方案吗?重新抛出 PDOException 时,我认为不适合使用异常链接(因为这只会使调试信息变得多余;DataAccessException 获取所有内容,包括来自 PDOException 的完整堆栈跟踪)。

提前致谢。

4

1 回答 1

0

据我了解你的帖子一个很好的资源是这样的: Api design

我认为您已经完成了作业(如果我可以使用该短语),但是您忘记了这样做的原因。在您的示例中,我将创建类似

SignUpException

这将通知上层注册出现问题。您在这里所做的基本上是用不同的名称来掩盖数据库异常,这本质上是同一件事,尽管在编程上是正确的,但首先忽略了为什么这样做的重点。

于 2009-11-28T00:35:53.587 回答