[英]Try Catch block should inserted in Controller or Model?
I have a structure project like follow: 我有一个如下的结构项目:
/Controller
test.php
/Models
test_model.php
Now when I execute a request the model test.php
shunk the request in the corresponding model, in this case test_model.php
. 现在,当我执行请求时,模型
test.php
在相应的模型(在本例中为test_model.php
了请求。 Here no problem. 这里没问题。 Now my question is: I should handle the exceptino in
test.php
class (controller) or in the test_model.php
class? 现在我的问题是:我应该在
test.php
类(控制器)还是在test_model.php
类中处理test_model.php
?
For execute all the database dialogue I have created a db layer with pdo. 为了执行所有数据库对话,我使用pdo创建了一个db层。 I set the:
我设置:
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
for handle the exception. 处理异常。 All working good but I have this doubt.
一切正常,但我对此表示怀疑。 A practice example:
一个实践示例:
<?php
include "test_model.php";
public function selectInformation()
{
try
{
$test = new Test_Model(); //just as example..
return $test->selectUserInfo(); // test_model
}catch(Exception $ex)
{
echo json_encode(array("success" => false, "message" => $ex->getMessage()));
exit();
}
}
...
Here the Test_Model
class: 这里是
Test_Model
类:
<?php
class Test_Model extends PDO
{
public function __construct()
{
parent::__construct();
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function selectUserInfo()
{
//I removed most part of the code, essentially here an exception is fired by a non correct db table name
}
Actually I manage all the exceptions in the Test
class but is a good practice? 实际上,我可以管理
Test
类中的所有异常,但这是一个好习惯吗? I use each Model
only for return a result from the database. 我仅将每个
Model
用于从数据库返回结果。 There is no each in the Model
class actually. 实际上,在
Model
类中没有每个。
Neither in the model or controller. 既不在模型中也不在控制器中。
An error exception have to be handled in the error handler. 错误异常必须在错误处理程序中进行处理。
Instead of "handling" every call to the model separately, you have to handle all errors in a single place. 不必单独“处理”对模型的每个调用,而必须在一个地方处理所有错误。 Which is called error handler.
这称为错误处理程序。
Neither error message or line number should be sent in JSON. 错误消息或行号均不应以JSON发送。 This information have to be logged locally, while no internal error have to be revealed outside.
此信息必须在本地记录 ,而没有内部错误必须暴露在外部。 Only a generalized excuse have to be shown.
只需要显示一个通用的借口。
There should be an error handler set through set_error_handler that have to be responsible for handling errors. 应该通过set_error_handler设置一个错误处理程序,该错误处理程序必须负责处理错误。 It should log errors in production, while only a generalized excuse sent outside.
它应该记录生产中的错误,而只有一个普遍的借口被发送到外面。
Note that it is very important to send appropriate HTTP status code in case of error, of 5xx family 请注意,在发生错误的情况下,发送5xx系列的适当的HTTP状态代码非常重要
您应该将try catch块放入控制器中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.