Php 使用异常控制应用程序流
我目前正在用PHP编写一个web应用程序,并决定使用异常(duh!) 对于在所有函数中放置try和catch块是否会被视为坏代码,我找不到答案 我目前正在使用异常来处理数据库错误(应用程序错误是通过一个简单的函数来处理的,该函数只将它们添加到数组中,然后将它们显示给用户)。try块放置在所有需要数据库连接的函数上 有关守则是:Php 使用异常控制应用程序流,php,oop,exception,Php,Oop,Exception,我目前正在用PHP编写一个web应用程序,并决定使用异常(duh!) 对于在所有函数中放置try和catch块是否会被视为坏代码,我找不到答案 我目前正在使用异常来处理数据库错误(应用程序错误是通过一个简单的函数来处理的,该函数只将它们添加到数组中,然后将它们显示给用户)。try块放置在所有需要数据库连接的函数上 有关守则是: public function db_conn_verify() { if(!isset($this->_mysqli)){ throw n
public function db_conn_verify()
{
if(!isset($this->_mysqli)){
throw new Exception("Network Error: Database connection could not be established.");
} else {
return Null;
}
}
以及使用此代码的示例函数:
public function get_users() {
try {
$this->db_conn_verify();
//Rest of function code
return True;
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
return False;
}
}
另外,是否最好扩展Exception类,然后使用新的Exception类来处理应用程序错误
谢谢我建议您使用以下内容:
public function get_users() {
try {
if( !isset($this->_mysqli) ) {
throw new Exception("Network Error: Database connection could not be established.");
}
//Rest of function code
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
}
我更喜欢使用我的exends of Exception,但都是一样的。对于exdending异常,您可以查看示例#5
编辑:要在数据库连接错误时立即使用try catch,您可以尝试以下操作:
try{
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
throw new Exception("Network Error: Database connection could not be established.");
}
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
在我提出解决方案之前,我一直在考虑这样做,但我在想的是,这将被复制很多次,这将使重新分解(如果需要)更长。也许你可以将try-catch块放在db-connection函数中,因此每次需要连接时,如果不工作,您会看到异常。但这会停止函数流吗?是的,因为异常会导致致命错误,停止所有进程。