Slim-Skeleton
Slim-Skeleton copied to clipboard
PHP warnings cause the response to be a mess consisting of a partial JSON and an error JSON
Steps to reproduce
- Create a new project with the slim skeleton
- Return a big JSON from an action (
return $this->respondWithData($bigJson)
) - Before returning the JSON, cause a PHP warning (e.g. by accessing a field from an associative array that doesn't exist)
What happens?
The server returns the action response partially, and then continues with the error JSON. So you get an invalid mess.
What would be expected?
The server returns the action response entirely. -or- The server returns the error JSON entirely.
Causes of the bug
When debugging I found out that the following happens:
- The action is executed, and its response is written with the
ResponseEmitter
. - The shutdown handler runs.
-
error_get_last()
returns something, so a new error response is created - The newly created
ResponseEmitter
tries to clean the output buffer withob_clean()
, but only the not yet flushed part of the big JSON is cleaned. What has been flushed (the first part of the big JSON) cannot be un-flushed. - The error JSON is appended.
Workaround 1
In public/index.php
, register a PHP error handler with set_error_handler
which throws an exception.
Workaround 2
Create a global flag which allows the reponse emitter to check if a response has already been written.
Disclaimer
I am new to PHP (only used it many many years ago) - so I might have misunderstood something.