LoginSignup
4
6

More than 5 years have passed since last update.

Slim3のwithJsonはステータスコードをデフォルトで200に書き換えていた

Last updated at Posted at 2016-01-14

この記事の内容はすでに修正されています

slimからjsonでエラーレスポンスを返そうとして

return $response->withStatus(500)->withJson([]);

ってやったらレスポンスのステータスコードが200で返ってきた
withJsonの実装読んでみると

public function withJson($data, $status = 200, $encodingOptions = 0)
{
    $body = $this->getBody();
    $body->rewind();
    $body->write(json_encode($data, $encodingOptions));

    return $this->withStatus($status)->withHeader('Content-Type', 'application/json;charset=utf-8');
}

現在のステータスコードに関係なく200で上書きするので注意
第二引数でステータスコード指定するかwithJsonした後にwithStatusしましょう

$response->withStatus(500)->withJson([]);

$response->withJson([])->withStatus(500);

でレスポンス変わっちゃうのはどうなんだろう

追記

https://github.com/slimphp/Slim/pull/1737
pull req送ってみたものの議論が始まって英語力が足りないのでついていけてないけど3.2.0で取り込んでもらえそう?

4
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6