我得到以下错误信息:
下面是我的代码:Exception([string $ Exception [, long $code [, Exception $previous = NULL]]])参数错误
class DAOException extends Exception {
function __construct($message, $code = 0, Exception $previous = null){
parent::__construct($message, $code, $previous);
}
我试着创建自己的异常,但它一直说我在这行有一个错误:
parent::__construct($message, $code, $previous).
下面是我调用这个异常的一个例子:
public function add(FilmDTO $filmDTO){
try{
$addPreparedStatement = parent::getConnection()->prepare(FilmDAO::ADD_REQUEST);
$addPreparedStatement->bindParam(':titre', $filmDTO->getTitre());
$addPreparedStatement->bindParam(':duree', $filmDTO->getDuree());
$addPreparedStatement->bindParam(':realisateur', $filmDTO->getRealisateur());
$addPreparedStatement->execute();
} catch(PDOException $pdoException){
throw new DAOException($pdoException->getMessage(), $pdoException->getCode(), $pdoException);
}
}
这是因为PDO异常可以有字母数字代码,而异常只能有整数代码。因此,在DAO构造函数中,当您将给定的代码(PDO代码—一个字符串)传递给异常构造时,它没有拥有它。
可以通过在DAOException构造函数中将代码强制转换为整数来解决这个问题。如果您需要完整的字符串代码(我不确定它是否为您提供了更多有用的信息),您始终可以将其追加或追加到消息字符串(同样,在DAOException构造函数中)
PDOException类::getCode()可能返回字符串:
getCode (void): mixed
它这样做,错误代码像HY1234
对FILTER_SANITIZE_NUMBER_INT
使用filter_var函数,得到代码编号1234
,不包含HY
。请记住,filter_var
返回的是字符串而不是整型,它可能返回false,因此为例如0设置一个默认异常代码,如下所示:
class DAOException extends Exception {
function __construct($message, $code = 0, Exception $previous = null){
//exception code coversion
$code = filter_var($code, 'FILTER_SANITIZE_NUMBER_INT);
if ($code === false) {
$code = 0;
} else {
$code = (int) $code;
}
parent::__construct($message, $code, $previous);
}
错误码的问题不是PDO异常所特有的,而是所有异常的普遍问题,参见这个问题:
PHP Exception::getCode()与Throwable接口相矛盾