cakephp 错误和异常处理
为了系统的顺利运行,需要有效地处理系统的故障。 cakephp 带有默认的错误捕获,它会在错误发生时打印并记录错误。相同的错误处理程序用于捕获 异常。
错误处理程序在调试为真时显示错误并在调试为假时记录错误。 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
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
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
this is cakephp tutorial and this is an example of passed arguments. argument-1: <!--?=$argument1 argument-2:


