在 PHP MVC 应用程序中处理可能的 MySQL 错误的最常见/最佳实践是什么?最好将模型中的成功布尔值传递给控制器还是抛出异常?假设我正在调用存储过程,我可能遇到的可能错误是数据库连接、用户没有权限、无效数据或随机 MySQL 错误,这可能是最有效/最有效的处理方法。
例如: 方法一:
//UserController.php
private function get_user_info(){
$user_info = $user_model->read_user_info(123);
if($user_info[0]){
//Do stuff with user data
}else{
//Check if db, permission, invalid data, or random MySQL error
}
}
//UserModel.php
public function read_user_info($read_user_id){
$stmt = $db->prepare("CALL read_user_info(?, ?)");
$stmt->bindParam(1, $current_user_id);
$stmt->bindParam(2, $read_user_id);
if($stmt->execute()){
$result_set = $stmt->fetchAll(PDO::FETCH_ASSOC);
//Does the user have permission to read other user's info
if($result_set["granted"]){
return array(true, $result_set["user_info"]);
}else{
return array(false, "Permission error");
}
}else{
return array(false, "MySQL error");
}
}
方法二:
//UserController.php
private function get_user_info(){
try{
$user_info = $user_model->read_user_info(123);
//Do stuff with user data
}catch(ConnectionException $e){
}catch(InvalidDataException $e){
}catch(MySQLException $e){
}
}
//UserModel.php
public function read_user_info($read_user_id){
$stmt = $db->prepare("CALL read_user_info(?, ?)");
$stmt->bindParam(1, $current_user_id);
$stmt->bindParam(2, $read_user_id);
if($stmt->execute()){
$result_set = $stmt->fetchAll(PDO::FETCH_ASSOC);
//Does the user have permission to read other user's info
if($result_set["granted"]){
return $result_set["user_info"];
}else{
throw new PermissionException();
}
}else{
throw new MySQLException();
}
}