PHP 处理业务逻辑错误。也许是设计模式?
关于如何处理业务逻辑错误有什么建议吗?我的意思不是例外。 例如,以免假设我有一个类:
<?php
class Reactor () { // business class
public function shutdown() {
if($date > '2 pm') {
// show error message to user
echo 'you can't shutdown before 2 pm.';
} else {
// error while trying to shutdown
throw new Exception('Oh my God, it is gonna blow!!');
}
}
}
?>
真正的问题是如何将错误消息传递给我的视图? 例外对于特殊情况有好处。我非常接近将 ErroMessage 和 ErrorCode 属性添加到基本业务类,并在每次调用业务类方法时检查它。
Any tips on how to handle business logic errors? I do not mean Exceptions.
For example, lest assume that i have a class:
<?php
class Reactor () { // business class
public function shutdown() {
if($date > '2 pm') {
// show error message to user
echo 'you can't shutdown before 2 pm.';
} else {
// error while trying to shutdown
throw new Exception('Oh my God, it is gonna blow!!');
}
}
}
?>
The real question is how to pass the error message to my views?
Exceptions are good for exceptional cases. I'm very close to add ErroMessage and ErrorCode attributes to the base business class and check it every time i call a business class method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您实际上走在正确的轨道上。您可以在 ErrorController 中处理异常 - 这是在 Zend 中建模的约定,但在许多其他框架中也是如此。如果您自己动手制作,则可以创建自己的。
该线程有一个更以 Zend 为中心的处理方法,但您可以使用 ErrorController 来实际渲染您的视图。处理 $e 异常类的输入并从中获取消息。
从模型/视图/控制器中抛出异常Zend Framework 应用程序
如果您深入 DIY 路线,如果您将较大的块包装在 try/catch 中并测试异常类的所有实例,则可以优雅地显示它。例如:
You're actually on the right track here. You can handle the exceptions in your ErrorController - a convention modeled in Zend, but in many other frameworks too. You can create your own if you're rolling it DIY.
This thread has a more Zend-centric method of handling, but you can use the ErrorController to actually render your view. Handle the input of the $e exception class and get the message from that.
Throwing exceptions from model/view/controller in a Zend Framework application
If you're deep in the DIY route, you can display it gracefully if you wrap your larger blocks in try/catch and test all instances of the exception class. For instance:
在这种情况下,异常正是您所需要的。状态验证(这就是您正在做的事情)将导致沉默或异常。您应该在控制器中处理模型抛出的异常,将它们转换为消息并将它们传递给视图。
Exceptions are exactly what you need in this case. State validation (this is what you're doing) shall lead either to silence or an exception. You shall handle Model-thrown exceptions in your Controller, convert them to messages and pass them to View.
我想你应该有这样的东西。
使用属性来存储数据和错误消息。我认为为
if
和else
生成错误也是不合逻辑的[更新]
I think you should have something like this.
Use attributes to store data and error message. And i think it is illogical to generate error for
if
andelse
too[UPDATE]