Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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で取り込んでもらえそう?

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした