How to add additional data to failed request of add action CRUD Api?
itodor opened this issue · 2 comments
I'm trying to add additional data to the API response when the POST request fails.
For example, when the request is successful and I need additional data along with entity I can do something like:
$this->Crud->on('afterSave', function (Event $event) {
$this->set('foo', 'bar');
$this->Crud->action()->serialize(['foo']);
});
I would need the same thing with the failed request but then it seems the error response is really hardcoded, can something be done about this or am I missing something obvious?
According to the docs Crud.afterSave
should be called both for success and failure, so it should work the same
Alternatively, you may be able to use Crud.beforeRender
Not really because its different code for success and failure, success callback in API listener calls this:
public function render(Subject $subject)
{
$this->injectViewClasses();
$this->_ensureSuccess($subject);
$this->_ensureData($subject);
$this->_ensureSerialize();
return $this->_controller()->render();
}
(note the ensureSerialize() method), while failed success just throws exception with this method
protected function _exceptionResponse(Event $Event, $exceptionConfig)
{
$exceptionConfig = array_merge($this->getConfig('exception'), $exceptionConfig);
$class = $exceptionConfig['class'];
if ($exceptionConfig['type'] === 'validate') {
$exception = new $class($Event->subject()->entity);
throw $exception;
}
$exception = new $class($exceptionConfig['message'], $exceptionConfig['code']);
throw $exception;
}
But you are right about the afterSave callback part because it does trigger in both cases but doesn't help in my case.