CakePHP 2.0 - customize database error message

心不动则不痛 提交于 2020-01-05 09:22:53

问题


I have a CakePHP 2.0 application with a MySQL database. Two database tables are connected with a 1:n relation and a foreign key constraint. So if I want to delete an entry which is connected in the other database table, I get the error:

Error: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a forein key constraint fails (...)
SQL Query: DELETE 'Test' FROM 'tests' AS 'Test' WHERE 'Test'.'id' = 10

Notice: If you want to customize this error message, create app/View/Errors/pdo_error.ctp

But what I want to do is to handle the error message! I read something about 'onError' but putting it into the 'AppModel' it seems not to be called (maybe it works only with CakePHP 1.3?):

class Test extends AppModel {
     function onError() {
         echo "TESTTESTTEST";
         $db = ConnectionManager::getDataSource('default');
         $err = $db->lastError();
         $this->log($err);
         $this->log($this->data);
     }
}

So what can I do? I want to remain on this page, and I want to show only an error message (not a stack trace and this kind of stuff).

Anyone an idea?


回答1:


What about using the .ctp?

If you want to customize this error message, create app/View/Errors/pdo_error.ctp

The one that's being used is in the Cake directory, you could just copy that to your app/View/Errors directory and remove the stack trace from that if you like.

There's also the beforeDelete() Model callback function you could use to set a flashMessage.




回答2:


Data base error normally give 500 error so cakephp handle 500 exception by using View/Errors/error500.ctp or app/View/Errors/pdo_error.ctp only and customize this page

and add this function bellow in AppController.php

 function beforeRender() {
    if($this->name == 'CakeError') {
        $this->set('title','Internal error occurs');
        $this->layout = 'frontend';
    }
    }


来源:https://stackoverflow.com/questions/8749449/cakephp-2-0-customize-database-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!