cakephp crud 插件 return 验证错误

cakephp crud plugin return validation errors

当使用 Crud pluginCrud.Api 侦听器 PATCHing 到记录时,成功的 PATCH returns 200 OK 响应中包含空数据数组。

{
    "success": true,
    "data": []
}

当 PATCH 后验证失败时,422 Unprocessable Entity 具有以下响应 returned:

{
    "message": "A validation error occurred",
    "url": "\/admin\/users\/edit\/4.json",
    "code": 422,
    "file": "\/app\/vendor\/friendsofcake\/crud\/src\/Listener\/ApiListener.php",
    "line": 189
}

但我希望是这样的:

{
    "success": false,
    "data": [
       "errors": [...]
    ]
    
}

https://crud.readthedocs.io/en/latest/listeners/api.html#http-put-edit

If success is false a HTTP response code of 422 will be returned, along with a list of validation errors from the model in the data property of the response body.

是否需要将插件配置为 return 错误?

我不太熟悉 Crud 插件,但该响应看起来像是默认的 CakePHP 异常渲染器响应,所以我猜您可能还没有将您的应用配置为使用 Crud 异常渲染器:

config/app.php

'Error' => [
    'exceptionRenderer' => \Crud\Error\ExceptionRenderer::class,
    // ...
],

引自文档:

Note: However if you are using CakePHP 3.3+’s PSR7 middleware feature the exceptionRenderer config won’t be used and instead you will have to set the Error.exceptionRenderer config in config/app.php to 'Crud\Error\ExceptionRenderer' as following

Crud Docs > Listeners > API > Exception handler