cakephp2.doc_051
R e i - D r e a m
for Laravel
TOP > CakePHP2 > View関連(エラーページ)
Guest
login

最終投稿日:2019年11月20日

View関連(エラーページ)
CakePHP1.3 CakePHP2.x
【missing回避】

    存在しない[controller名][action名]をURLに指定すると
    Missing... と表示されてしまいます。

    これを回避するには、

    [views]->[errors]に
        [missing_action.ctp]
        [missing_controller.ctp]
    上記2つのファイルを設置します。

    エラーの際にはそれぞれのビューを参照するようになります。
    
    【注意】
        ファイル容量が512バイト以上ないとIEでリンク切れのページになる可能性があります。
            
【エラーページのレイアウト変更】

    エラーページ・イアウトは[app][View][Layouts][default.ctp]を参照します。
    これを変更するには、

        [lib][Cake][Controller][CakeErrorController.php]をコピーし、
        [app][Controller][CakeErrorController.php]と貼り付けます。

            parent::__construct($request, $response);
            $this->layout = 'my_error';

            上記の様に parent::~ の下あたりにレイアウトの指定をすれば良い。

            ※当然だが[app][View][Layouts][my_error.ctp]を作成する。


【例外の設定】

    例外の設定をし、throw する事によりエラーページを表示する事もできます。

    < 例外の設定 >
        全体に影響を与えたければ AppController.php の beforeFilter() メソッドに記述する

        Configure::write('Exception', array(
            //コールバックの指定
            'handler' => 'ErrorHandler::handleException',
            //どのレンダークラスを使用するか
            'renderer' => 'ExceptionRenderer',
            //ログを記録するか
            'log' => true
        ));

        ※ちなみに上記内容は [app][Config][core.php]のデフォルト設定なので省略できます。


    < スローする >
        あとは以下の様に例外を発生させたい箇所で throw すれば良い。

            //400 Bad Request エラーを発生させるために使います
            throw new BadRequestException("hoge");

        ◆その他の例外

            //403 Forbidden エラーを発生させるために使います
            ForbiddenException
            //404 Not found エラーを発生させるために使います
            NotFoundException
            //405 Method Not Allowed エラーを発生させるために使います
            MethodNotAllowedException
            //500 Internal Server Error を発生させるために使います
            InternalErrorException
            //501 Not Implemented Errors を発生させるために使います
            NotImplementedException

            ※基本的に全て引数の内容がエラーとして出力される。


        メモ)
            エラー画面に以下の様な内容も表示される

                Error: The requested address~
                Error: An Internal Error Has Occurred.

            これは[app][View][Errors][error400.ctp]及び
             [app][View][Errors][error500.ctp]の以下の部分で生成しています。

                    ~ 省略 ~

            ※スローした例外が 400系か500系かで振り分けられる。



【オリジナルの例外の設定】

    設定の renderer を変更する事により独自の例外ページを作成できる。

    < 例外の設定 >
        全体に影響を与えたければ AppController.php の beforeFilter() メソッドに記述する

        Configure::write('Exception', array(
            'handler' => 'ErrorHandler::handleException',
            //このファイルを独自ファイルにする
            'renderer' => 'HogeExceptionRenderer',
            'log' => false
        ));


    < 独自ファイルの作成 >

    [app][Lib]に[Error]ディレクトリを作成し、先ほどの独自ファイルを作成する。

        [app][Lib][Error][HogeExceptionRenderer.php]

        <?php
            App::uses('ExceptionRenderer', 'Error');
            App::uses('Sanitize', 'Utility');
            App::uses('Router', 'Routing');
            App::uses('CakeResponse', 'Network');
            App::uses('Controller', 'Controller');

            class HogeExceptionRenderer extends ExceptionRenderer {

                public $controller = null;
                public $method = '';
                public $error = null;
                public $code = '';
                
                //コンストラクタ
                public function __construct(Exception $exception) {
                    //もともとのクラス[lib][Cake][Error][ExceptionRenderer.php]
                    //のコンストラクタをコピー
                    $this->controller = $this->_getController($exception);

                    if (method_exists($this->controller, 'apperror')) {
                        return $this->controller->appError($exception);
                    }
                    $method = $template = Inflector::variable(
                        str_replace('Exception', '', get_class($exception)));
                    $code = $exception->getCode();

                    $methodExists = method_exists($this, $method);

                    if ($exception instanceof CakeException && !$methodExists) {
                        $method = '_cakeError';
                        if (empty($template) || $template === 'internalError') {
                            $template = 'error500';
                        }
                    } elseif ($exception instanceof PDOException) {
                        $method = 'pdoError';
                        $template = 'pdo_error';
                        $code = 500;
                    } elseif (!$methodExists) {
                        $method = 'error500';
                        if ($code >= 400 && $code < 500) {
                            $method = 'error400';
                        }
                    }

                    $isNotDebug = !Configure::read('debug');
                    if ($isNotDebug && $method === '_cakeError') {
                        $method = 'error400';
                    }
                    if ($isNotDebug && $code == 500) {
                        $method = 'error500';
                    }
                    $this->template = $template;
                    $this->method = $method;
                    $this->error = $exception;
                }

                //400系のエラーはこのメソッドが呼ばれる
                public function error400($error){
                    //お約束の値をセット
                    $this->controller->set(array("error"=>$error,"name"=>$error->getMessage()
                        ,"url"=>$this->controller->request->here()));
                    //レンダリングするテンプレートを指定
                    $this->controller->render("error400");
                    //レンダリングする
                    $this->controller->response->send();
                }

                //500系のエラーはこのメソッドが呼ばれる
                public function error500($error){
                    $this->controller->set(array("error"=>$error,"name"=>$error->getMessage()
                        ,"url"=>$this->controller->request->here(),"code"=>$error->getCode()));
                    $this->controller->render("error500");
                    $this->controller->response->send();
                }
            }
        ?>

        ※取得できるメソッド

            //スローに設定した第1引数
            $error->getMessage();
            //スローに設定した第2引数
            $error->getCode();
            //リクエストしたURL
            $this->controller->request->here();

    メモ)
        例外をスローする際には例えば throw new BadRequestException("エラー");とる。
        500系の例外には第2引数に コード を渡す事ができる。
        ただし400系の例外にも第2引数を渡してもエラーとはならないが、
            強制的に500系の例外が呼ばれる仕様となっている。
            
ログインしてコメントを残そう!!


きっぷる