Search code examples
phptry-catch

catch is running even with code going right


I'm using try catch on my application, but everything on try works, but still returning the catch. the register is saved on DB, but still on catch

        try
        {

                    $sql = new Sql();
                    $results = $sql->select("CALL sp_save_lead(:name, :email, :phone, :idOrigin, :comments)", array(
                            ":name"=>$this->getname(),
                            ":email"=>$this->getemail(),
                            ":phone"=>$this->getphone(),
                            ":idOrigin"=>$this->getid_Origin(),
                            ":comments"=>$this->getcomments()
                    )); 

                        //$this->setData($results[0]);

                        $id = $results[0]["idLead"];

        } catch (\Exception $e) {
                        header("Location: /admin/leads/?msg=Error");
                        exit;
        } finally {
                        header("Location: /admin/leads/".$id."/?msg=Success");
                        exit;
        }

Must execute finally


Solution

  • Solved, I was expecting and normal PHP Exception, I should expect a PDOException. So I just changed the following:

    "} catch (\Exception $e) {" to "} catch (\PDOException $e) {"

        try
        {
    
                    $sql = new Sql();
                    $results = $sql->select("CALL sp_save_lead(:name, :email, :phone, :idOrigin, :comments)", array(
                            ":name"=>$this->getname(),
                            ":email"=>$this->getemail(),
                            ":phone"=>$this->getphone(),
                            ":idOrigin"=>$this->getid_Origin(),
                            ":comments"=>$this->getcomments()
                    )); 
    
                        //$this->setData($results[0]);
    
                        $id = $results[0]["idLead"];
    
        } catch (\PDOException $e) {
                        header("Location: /admin/leads/?msg=Error");
                        exit;
        } finally {
                        header("Location: /admin/leads/".$id."/?msg=Success");
                        exit;
        }