简体   繁体   English

尝试catch块不适用于成功返回

[英]try catch block is not working with success return

In my code, when the function throws an error such as, organisation name is required or it is alread exists, the catch block works properly. 在我的代码中,当函数引发错误(例如,需要组织名称或该名称已经存在)时,catch块将正常工作。 But in the case of success, eventhough the corresponding organisation is inserted,i got the status of 200 with error message. 但是在成功的情况下,即使插入了相应的组织,我仍会得到状态200,并显示错误消息。 What is the mistake in my code. 我的代码有什么错误?

insertTenancy is the function written in Mycontroller. insertTenancy是用Mycontroller编写的函数。

 public function insertTenancy($data,$user, $res)
{

    $org_name = $data['org_name'];
    $queryString = "SELECT * FROM organisation WHERE name = ? and user_id =?";
    $query = $this->db->prepare($queryString);
    $query->execute([$org_name,$user]);

    if($query->fetch(\PDO::FETCH_ASSOC)){
        //throw new Exception('This organisation is already in use');
        return CCommon::prepareError($res, 'This organisation is already in use', 403);
    }

     $insertOrg = "INSERT INTO organisation (currency_id,name,user_id) VALUES (1,:name,:user_id)";

        $insertOrgname = $this->db->prepare($insertOrg);
        $insertOrgname->bindParam(':name', $org_name);
        $insertOrgname->bindParam(':user_id', $user_id);
        $insertOrgname->execute();
        $lastorgId = $this->db->lastInsertId();
        return $lastorgId;
 }

Following function written in routerContainer 用routerContainer编写的跟随函数

try
    {
        $postData = $request->getParsedBody();
        $currentUser = $this->user;
        $data = array();
        $data = $this->MyController->insertTenancy($postData,$currentUser,$response);
            echo json_encode($data);
            exit;
    }
    catch (Exception $e)
    {
        $data = array();
        $data['success'] = false;
        $data['message'] = $e->getMessage();
        return CBCommon::prepareError($response, $data['message'], 403);
        exit;
    }

You create a new array then you add false to the index 'success'. 创建一个新数组,然后将false添加到索引“成功”。

So why should 那为什么要

$data['message']

be defined? 被定义?

Maybe you want change your 也许你想改变你的

$error 

into 进入

 $data['message']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM