CakePHP - 错误和异常处理

为了使系统平稳运行,需要有效地处理系统故障。CakePHP 带有默认错误捕获功能,可在错误发生时打印和记录错误。此错误处理程序还用于捕获异常

当 debug 为 true 时,错误处理程序显示错误;当 debug 为 false 时,错误处理程序记录错误。CakePHP 有许多异常类,内置的异常处理将捕获任何未捕获的异常并呈现有用的页面。

错误和异常配置

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

选项 数据类型 描述
errorLevel int

您感兴趣的错误级别。使用内置的 php 错误常量和位掩码来选择您感兴趣的错误级别。

trace bool

在日志文件中包含错误的堆栈跟踪。每次错误发生后,堆栈跟踪都会包含在日志中。这有助于查找错误发生的位置/时间。

exceptionRenderer string

负责呈现未捕获异常的类。如果您选择自定义类,则应将该类的文件放在src/Error中。此类需要实现 render() 方法。

log bool

当为 true 时,异常及其堆栈跟踪将记录到 Cake\Log\Log

skipLog array

不应记录的异常类名数组。这对于删除 NotFoundExceptions 或其他常见但不感兴趣的日志消息很有用。

extraFatalErrorMemory int

设置为遇到致命错误时增加内存限制的兆字节数。这为完成日志记录或错误处理提供了喘息空间。

示例

config/routes.php 文件中进行更改,如以下代码所示。

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('/exception/:arg1/:arg2',
      ['controller'=>'Exps','action'=>'index'],
      ['pass' => ['arg1', 'arg2']]);
   $builder->fallbacks();
});

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

src/Template/Exps/index.php

这是 CakePHP 教程,这是传递参数的示例。
参数 1:<?=$argument1?><br/> 参数 2:<?=$argument2?><br/>

通过访问以下 URL 执行上述示例。

http://localhost/cakephp4/exception/5/0

输出

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

Arguments