CakePHP 错误和异常处理
为了系统的平稳运行,需要有效地处理系统的故障。 CakePHP 带有默认的错误捕获,在错误发生时打印并记录错误,这个错误处理程序也被用来捕捉异常。
错误处理程序在调试为真时显示错误并在调试为假时记录错误,CakePHP 有许多异常类,内置的异常处理将捕获任何未捕获的异常并呈现有用的页面。
错误和异常配置
错误和异常可以在config\app.php文件中配置,错误处理接受一些选项,允许你为应用程序定制错误处理:
选项 | 数据类型 | 描述 |
---|---|---|
errorLevel | int | 你想要捕获的错误级别,使用内置的 php 错误常量和位掩码来选择你想要的错误级别。 |
trace | bool | 在日志文件中包含错误的堆栈跟踪,每次错误后,堆栈跟踪将包含在日志中,这有助于查找发生错误的位置/时间。 |
exceptionRenderer | string | 负责呈现未捕获的异常的类,如果你选择一个custom类,你应该将该类的文件放在src/Error,这个类需要实现一个render()方法。 |
log | bool | 当为真时,异常 + 它们的堆栈跟踪将被记录到Cake\Log\Log。 |
skipLog | array | 不应记录的异常类名称数组,这有助于剔除NotFoundExceptions或其他常见但无趣的日志消息。 |
extraFatalErrorMemory | int | 设置为在遇到致命错误时,增加内存限制的兆字节数,这为完成日志记录或错误处理提供了容错空间。 |
修改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文件,并将以下代码复制到该文件中:
<?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文件,并将以下代码复制到该文件中:
This is CakePHP tutorial and this is an example of Passed arguments. Argument-1: <?=$argument1?><br/> Argument-2: <?=$argument2?><br/>
访问http://localhost/cakephp4/exception/5/0执行上述示例,输出如下所示: