php - 在 beforeSave() 和停止 save() 调用上从 CakePHP 3.8 模型返回自定义 422 实体错误的正确方法是什么?
问题描述
我目前正在向基于 Cake 3.8 的 API 添加 422 个 http 验证错误。
对于任务控制器,我有类似的东西:
<?php
class TasksController extends AppController
{
public function initialize()
{
parent::initialize();
}
public function add(string $id): void
{
$validationErrors = [];
$task = $this->newEntity($this->request->getData(););
if ($this->Tasks->save($task)) {
// Errors added to entity in before save will not cause
// save() to return false and stop the proccess from
// making it here
$this->response = $this->response->withStatus(200);
} else {
$validationErrors = [$task->getErrors()];
if (count($validationErrors) > 0) {
$this->response = $this->response->withStatus(422);
} else {
throw new BadRequestException("The posted entity is is invalid.");
}
}
// Render json output for success / errors
$this->set($this->createViewVars(['entity' => $task], $validationErrors));
}
}
对于 TasksTable 我有类似的东西:
<?php
class TasksTable extends AppTable
{
public function initialize(array $config)
{
parent::initialize($config);
}
public function beforeSave(Event $event, Entity $task, ArrayObject $options)
{
parent::beforeSave($event, $task, $options);
$task->setError('technician', 'No default technician was able to be found');
if(count($task->getErrors()) > 0) {
$event->stopPropagation();
}
}
}
在 beforeSave 和 beforeMarshal 上编译数据的某些进程可能会检测到添加请求与系统配置不兼容的问题,这些进程需要抛出验证错误。
第1部分:
上表中的当前代码能够在表的 beforeSave 方法中捕获错误并使用 $event->stopPropagation() 停止数据库事务。但是我想知道从表中返回带有错误的未保存任务实体的正确方法是什么?我可以将实体存储到任务模式并使用自定义 getter 来执行此操作,但似乎会有一些内置功能来处理这个?
第2部分:
有没有一种方法可以触发 $this->Tasks->save($task) 在 beforeSave 中失败(返回 false)以及使用 $event->stopPropagation() 停止查询?
提前致谢!
解决方案
推荐阅读
- c# - var 关键字可以将变量类型更改为动态吗?
- python - 如何正确安装手电筒?
- http - Flutter 中的 HTTP POST 获取 Cookie
- laravel - 重定向到受中间件 laravel 保护的路由
- angular - 如何在前端的 IIS Windows 身份验证中获取用户名?
- python-3.x - 我需要能够打印出星号模式,要求用户输入行数
- typescript - keyof typeof StaticClass 似乎包括 StaticClass' 类型本身
- flutter - 无法在颤振中检索保存的图像(仅在 iOS 上可重现的问题)
- mongodb - Querying nested object arrays
- php - 从 WordPress 小部件获取数据以修改帖子内容