有关如何处理业务逻辑错误的任何提示?我不是指例外情况。 例如,以免我假设我有一个类:
<?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属性添加到基本业务类,并在每次调用业务类方法时检查它。
答案 0 :(得分:2)
你实际上是在正确的轨道上。您可以在ErrorController中处理异常 - 一种在Zend中建模的约定,但在许多其他框架中也是如此。如果你正在DIY它,你可以创建自己的。
此线程具有更多以Zend为中心的处理方法,但您可以使用ErrorController实际呈现视图。处理$ e异常类的输入并从中获取消息。
Throwing exceptions from model/view/controller in a Zend Framework application
如果您深入DIY路线,如果将较大的块包装在try / catch中并测试异常类的所有实例,则可以优雅地显示它。例如:
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!!');
}
}
}
//later, in the controller
$reactor = new Reactor();
try{
$reactor->shutdown('1pm');
} catch(Your_Custom_Exception $e){
//pass to view
$this->view($e->getMessage());
} catch(Exception $e){
// woops, serious error. do something useful
}
答案 1 :(得分:2)
在这种情况下,例外正是您所需要的。状态验证(这是你正在做的事情)将导致沉默或异常。您应该在Controller中处理模型抛出的异常,将它们转换为消息并将它们传递给View。
答案 2 :(得分:1)
我认为你应该有类似的东西。
使用属性存储数据和错误消息。我认为为if
和else
生成错误
class Reactor{
public $date;
public $error;
public $errorstatus = false;
//Use property to store data and errors
public function shutdown() {
if($date > 2) {
$this->errorstatus = true;
$this->error['date'] = "You cannot shutdown before 2 pm";
} else
return true;
}
}
$reactor = new Reactor();
$reactor->data = 3;
$reactor->shutdown();
if($reactor->errorstatus){
echo $reactor->error['date'];
}
else{
echo "Its already two you can shutdown";
}
echo "<br/>";
$reactor->data = 1;
$reactor->shutdown();
if($reactor->errorstatus){
echo $reactor->error['date'];
}
else{
echo "Its already two you can shutdown";
}
[UPDATE]
public function shutdown() {
if($date > 2) {
$this->errorstatus = true;
$this->error['date'] = "You cannot shutdown before 2 pm";
} else
if($this->poweroff)
return true;
else
throw new Exception("ERROR WHILE SHUTTING DOWN"):
}
private function poweroff()
{
//if power off then return true
//else return false
}