-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Labels
Description
Once HTTP headers are sent, exceptions become badly handled.
This is because the server can no longer control the HTTP status code being sent.
This code throws a runtime exception after the headers are sent.
It is best to avoid this behavior if possible.
The following is a suggested solution:
$json = json_encode($this->getViewVariables());
if ($json === false) {
throw new \RuntimeException($this->getEncodeErrors()[json_last_error()]);
}
header('Content-Type: application/json;charset=utf-8');
echo $json;This also solves a secondary issue where the json_encode() could return an empty string.
An empty string could be returned and the if ($json) would return an exception when there is no JSON last error.
Or it could return the wrong last error because the most recent call did not fail but another call may have failed.
see:
| header('Content-Type: application/json;charset=utf-8'); |