在我的php页面中,我正在尝试与数据库进行交互,并且如果出现错误,我想返回一些特定的值。问题是我不能抛出异常。
在下面的函数中,如果数据库操作失败,我会抛出一些异常。当我尝试向数据库中已经存在的userEmail注册时,第二个查询应该抛出错误,因为userEmail属性在我的数据库中是唯一的。
根据应该在catch块中触发的返回值,我试图在页面上显示一些警报。但是,当我尝试时,没有抛出异常,函数只会返回true。
public function registerServer($user, $pass)
{
try
{
$dbLink = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$dbLink)
{
throw new Exception("dbFailure");
}
$user = mysqli_real_escape_string($dbLink, $user);
$hashedPass = hash("ripemd128", $pass);
/* userID is inserted NULL because it is autoincremented - userEmail is unique in db.
That means in case of attempt to registeration of existing user, this block throws an exception */
if (!$dbLink->query("INSERT INTO userData (userID, userEmail, userPass, userStatus) VALUES (NULL, '$user', '$hashedPass', 'passive')"))
{
throw new Exception("userExists");
}
mysqli_close($dbLink);
return TRUE;
}
catch (Exception $e)
{
if($e->getMessage() == "dbFailure")
return "dbFailure";
else if($e->getMessage() == "userExists")
{
mysqli_close($dbLink);
return "userExists";
}
else
return "exception";
}
}
即使我尝试这样做:
public function registerServer($user, $pass)
{
try
{
throw new Exception("dbFailure");
}
catch (Exception $e)
{
if($e->getMessage() == "dbFailure")
return "dbFailure";
}
}
仍然没有。我想我错过了一些理论要点。感谢您的关注!