【问题标题】:Some exceptions are not being caught一些异常没有被捕获
【发布时间】:2014-12-17 17:42:45
【问题描述】:

我正在创建一个简单的 API。我有一个index.php 文件,所有对 API 的请求都会通过。 index.php 处理请求的参数以确定使用哪个控制器和操作。所有这些都包含在try/catch 块中,因此每当我需要为客户端生成错误消息时,我都可以throw new Exception()。这一直按预期工作,但现在我创建了一个处理用户注册和登录的用户类。在注册操作中,我检查从客户端应用程序传递的用户名是否已经存在于数据库中,如果存在,我 throw new Exception('Username already exists!')。但是,这并没有被我的catch 发现。相反,我收到的是正常的Fatal error: uncaught exception 消息。这是我的index.php代码

include_once 'models/UserItem.php';

try {

    $enc_request = $_REQUEST['enc_request'];

    $app_id = $_REQUEST['app_id'];
    if( !isset($applications[$app_id]) ) {
      throw new Exception('Application does not exist!');
    }


    $params = json_decode(trim(mcrypt_decrypt( MCRYPT_RIJNDAEL_256, $applications[$app_id], base64_decode($enc_request), MCRYPT_MODE_ECB )));
    if( $params == false || isset($params->controller) == false || isset($params->action) == false ) {
        throw new Exception('Request is not valid');
    }

    $params = (array) $params;

    $controller = ucfirst(strtolower($params['controller'])); //User


    $action = strtolower($params['action']).'Action'; //registerAction

    if( file_exists("controllers/{$controller}.php") ) {
        include_once "controllers/{$controller}.php";
    } else {
        throw new Exception('Controller is invalid.');
    }


    $controller = new $controller($params);

    if( method_exists($controller, $action) === false ) {
        throw new Exception('Action is invalid.');
    }

    $result['data'] = $controller->$action();
    $result['success'] = true;

} catch( Exception $e ) {
    $result = array();
    $result['success'] = false;
    $result['errormsg'] = $e->getMessage();
}

发送给请求的参数在一个数组中如:

array(
    'controller' => 'user',
    'action' => 'register',
    'username' => $_POST['username'],
    'userpass' => $_POST['userpass']
);

index.php 中的代码然后调用我的user controller 中的registerAction(),即:

public function registerAction() {
    $user = new UserItem();
    $user->username = $this->_params['username'];
    $user->password = $this->_params['userpass'];

    $user->user_id = $user->save();

    return $user->toArray();
}

然后这段代码在我的UserItem model 中调用save 方法,即:

public function save() {
        $db = new Database();
        $db->query('select * from users where username = :user');
        $db->bind(':user', $this->username);
        $r = $db->single();

        if ( $r ) {
            throw new Exception('Username already exists! Please choose another.');
        }

        else {
            $db->query('insert into users(username, password) values(:username, :password)');
            $db->bind(':username', $this->username);
            $db->bind(':password', $this->password);    

            $r = $db->execute();

            $user_array = $this->toArray();

            if ( !$r ) {
                throw new Exception('There was a problem creating your account. Please try again later.');
            }
        }

        return $db->lastInsertId();

}

服务器抛出异常,只是没有被正确捕获。有没有人看到我在 try/catch 方面做错了什么?

谢谢

【问题讨论】:

    标签: php exception try-catch


    【解决方案1】:

    在这里你抛出了一个异常,但你没有捕获到异常。要实现这一点,您必须在 try/catch 块内实现以处理捕获的异常。这是一个实现尝试的示例。

    try{
    $user->user_id = $user->save();
    }catch(Exception $e){
    echo "caught Exception :".$->getMessage();
    }
    

    我希望它能解决您的问题。谢谢。

    【讨论】:

    • 如果您查看上面的代码,您会发现所有内容都包含在 try/catch 中。那么管道中发生的任何异常都应该触发catch 对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2013-08-08
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多