Cakephp 2.5.4:数据库错误错误:SQLSTATE [23000]:完整性约束违规:1062重复条目

时间:2014-09-21 08:03:34

标签: cakephp

我想在cakephp中显示数据库的错误。如何向用户显示“sql错误”消息。这是我的代码。在这段代码中,我收到了数据库错误。但我希望向用户显示正确的消息而不是数据库错误。

public function edit_mothertongue(){    
    $motherTongue=array();
    if($this->request->is('post')){
        foreach ($this->request->data as $key => $value) {
        $motherTongue[$key]=$value;
        }
        if(!empty($motherTongue)){
            App::import('Model','MotherTongue');
            $this->MotherTongue=new MotherTongue();
            try{
                if($this->MotherTongue->save($motherTongue)){
                    echo "Record saved";
                }else{
                    echo "Record not saved";
                }
            }
            catch(Exception $e){
                echo $e->getMessage(); // I want to display error message of sql.
            }
        }       
    }       

}

2 个答案:

答案 0 :(得分:1)

如果要显示信息,则需要使用视图。要将信息从控制器传递到视图,请使用set方法。

$this->set('errormsg', $e->getMessage());

然后在您的视图中使用$errormsg

答案 1 :(得分:1)

如果您想使用AJAX,可以这样设置:

        $this->set('_serialize', array('errormsg'));

如果您正在寻找JSON的输出

然而,使用AJAX超出了这个问题的范围。