Cakephp-errors-exception-handling

提供:Dev Guides
移動先:案内検索

CakePHP-エラーと例外処理

システムの障害は、システムの円滑な実行のために効果的に処理される必要があります。 CakePHPには、発生したエラーを出力して記録するデフォルトのエラートラップが付属しています。 この同じエラーハンドラを使用して、*例外*をキャッチします。 デバッグがtrueの場合、エラーハンドラーはエラーを表示し、debugがfalseの場合、エラーをログに記録します。 CakePHPには多数の例外クラスがあり、組み込みの例外処理により、キャッチされなかった例外をキャプチャし、有用なページをレンダリングします。

エラーと例外の構成

エラーと例外はファイル config \ app.php で設定できます。 エラー処理は、アプリケーションのエラー処理を調整できるいくつかのオプションを受け入れます-

Option Data Type Description
errorLevel int The level of errors you are interested in capturing. Use the built-in php error constants, and bitmasks to select the level of error you are interested in.
trace bool Include stack traces for errors in log files. Stack traces will be included in the log after each error. This is helpful for finding where/when errors are being raised.
exceptionRenderer string The class responsible for rendering uncaught exceptions. If you choose a custom *class, you should place the file for that class in src/Error*. This class needs to implement a *render() *method.
log bool When true, exceptions + their stack traces will be logged to* Cake\Log\Log*.
skipLog array An array of exception classnames that should not be logged. This is useful to remove NotFoundExceptions or other common, but uninteresting logs messages.
extraFatalErrorMemory int Set to the number of megabytes to increase the memory limit by when a fatal error is encountered. This allows breathing room to complete logging or error handling.

次のコードに示すように、 config/routes.php ファイルに変更を加えます。

*config/routes.php*
<?php
   use Cake\Core\Plugin;
   use Cake\Routing\RouteBuilder;
   use Cake\Routing\Router;

   Router::defaultRouteClass('DashedRoute');
   Router::scope('/', function (RouteBuilder $routes) {
      $routes->connect('/exception/:arg1/:arg2',[
         'controller'=>'Exps','action'=>'index'],['pass' => ['arg1', 'arg2']]);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();
*src/Controller/ExpsController.php* に *ExpsController.php* ファイルを作成します。 次のコードをコントローラーファイルにコピーします。
*src/Controller/ExpsController.php*
<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Core\Exception\Exception;

   class ExpsController extends AppController{
      public function index($arg1,$arg2){
         try{
            $this->set('argument1',$arg1);
            $this->set('argument2',$arg2);

            if(($arg1 < 1 || $arg1 > 10) || ($arg2 < 1 || $arg2 > 10))
            throw new Exception("One of the number is out of range[1-10].");
         }catch(\Exception $ex){
            echo $ex->getMessage();
         }
      }
   }
?>
*src/Template* に *Exps* ディレクトリを作成し、そのディレクトリの下に *index.ctp* という *View* ファイルを作成します。 そのファイルに次のコードをコピーします。
*src/Template/Exps/index.ctp*
This is CakePHP tutorial and this is an example of Passed arguments.
Argument-1: <?=$argument1?>
Argument-2: <?=$argument2?>

次のURLにアクセスして、上記の例を実行します。

*http://localhost:85/CakePHP/exception/5/0*

出力

実行すると、次の出力が表示されます。

例外