处理数据库错误

发布于 2024-12-09 03:24:12 字数 450 浏览 0 评论 0原文

我在应用程序中使用 MVC 框架,因此当前当我在模型中使用数据库时检测到发生错误时,我会将异常抛出回控制器。

//db querying
//doing more db querying...
if (error)
    throw new ApiException('Unable to connect to User database', 1, 500);
else if (another type of error)
    throw new StampApiException('Could not retrieve the User', 12, 500);

return $user;

大多数时候,我发现这很好,因为我可以让控制器将错误打印到屏幕上,从而将所有错误代码等保留在模型中。但有时这会使代码变得非常混乱并且难以处理。

这是处理此类错误的好方法吗?或者有更好/更标准的方法吗?

I am using an MVC framework in my application, so currently when I detect an error has occurred while working with the database in my model, I am throwing exceptions back to the controller.

//db querying
//doing more db querying...
if (error)
    throw new ApiException('Unable to connect to User database', 1, 500);
else if (another type of error)
    throw new StampApiException('Could not retrieve the User', 12, 500);

return $user;

Most of the time I find this to be nice as I can just have the controller print the error to the screen, thus keeping all error codes etc... in the model. But at times this can make the code quite messy and harder to deal with.

Is this a good way to be handling such errors? Or is there a better/more standard way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

就此别过 2024-12-16 03:24:12

首先,我想说用户不需要知道问题是数据库、管理员密码还是内存。只需为用户提供一个技术错误页面,并将错误详细信息记录在服务器上,以供调试。

对于你所说的技术问题,最好是有一个集中处理来管理它们,即抛出一个错误页面。
通常的地方是控制器的调度程序。如果您使用框架,则应该存在此机制(例如 symfony)。
这样,您就不必在实际代码中弄乱这些异常。

就像您发现的那样,最好的策略是仅当您可以采取措施时才捕获异常。

例如:

  • “数据库访问问题”可以由
    调度员。所以你不会在代码中捕获它,而是让它传递给
    集中处理
  • “未找到用户”可能会受到控制器的特定处理,
    例如提出创作。所以你抓住了它。

Fisrt, I would say the user does not need to know if the problem is the database, the admin password or the memory. Just have a technical error page for the user, and log the error detail on the server, for your debug.

For the technical problems you are talking about, the best is to have a central treatment to manage them, i.e. throw an error page.
The usual place is the dispatcher of the controller. If you're using a framework, this mechanism should exist (symfony for example).
This way, you don't have to mess with these exceptions in your actual code.

Just like you found it, the best policy is to catch an exception only when you can do something about it.

For example :

  • a "database access problem" can be automatically treated by the
    dispatcher. So you don't catch it in your code en let it to the
    central treatment
  • a "user not found" may have a specific treatment from your controller,
    to propose creation for example. So you catch it.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文