Skip to content

Don't prematurely send HTTP headers when sending JSON view results. #103

@kaladay

Description

@kaladay

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');

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions