目录

CakePHP - 服务( Services)

为了系统的平稳运行,需要有效地处理系统故障。 CakePHP带有默认错误捕获,可以在出现错误时打印并记录错误。 此错误处理程序用于捕获Exceptions 。 debug为true时错误处理程序显示错误,debug为false时记录错误。 CakePHP有许多异常类,内置的异常处理将捕获任何未捕获的异常并呈现有用的页面。

错误和异常配置

可以在文件config\app.php配置错误和异常。 错误处理接受一些选项,允许您为应用程序定制错误处理 -

选项 数据类型 描述
errorLevelint 您有兴趣捕获的错误级别。 使用内置的php错误常量和位掩码来选择您感兴趣的错误级别。
tracebool 在日志文件中包含错误的堆栈跟踪。 每次出错后,堆栈跟踪都将包含在日志中。 这有助于查找错误发生的位置/时间。
exceptionRendererstring 负责呈现未捕获异常的类。 如果选择custom类,则应将该类的文件放在src/Error 。 该类需要实现render()方法。
logbool 如果为true,则异常+其堆栈跟踪将记录到Cake\Log\Log
skipLogarray 不应记录的异常类名数组。 这对于删除NotFoundExceptions或其他常见但不感兴趣的日志消息很有用。
extraFatalErrorMemoryint 设置为兆字节数,以便在遇到致命错误时增加内存限制。 这允许呼吸空间来完成记录或错误处理。

例子 (Example)

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.ctpView文件。 复制该文件中的以下代码。

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

输出 (Output)

执行后,您将收到以下输出。

例外
↑回到顶部↑
WIKI教程 @2018