【问题标题】:SlimFramework php v3, withStatus(500) does not workSlimFramework php v3,withStatus(500) 不起作用
【发布时间】:2017-06-30 11:28:32
【问题描述】:

我开始学习 PHP Slim-Framework v3。但我发现在少数情况下很难。

这是我的代码:

$app = new \Slim\App(["settings" => $config]);
$app->get('/', function(Request $request, Response $response, $args = []) {
    $error = array('result' => false, 'message' => 'Bad Request', 'dev'=>'', 'data' => []);
    $response->withStatus(500)->getBody()->write(json_encode($error));
});

现在,当我在服务中遇到问题时,我想向用户回复状态 500。但不幸的是,这不起作用。虽然我收到了响应,但它返回的是 200 状态而不是 500。

我做错了什么还是错过了什么?

我尝试调查其他问题,但没有找到任何帮助。

【问题讨论】:

  • 旁白(?):如果请求不好,500是错误的响应码; 400 是正确的。
  • 是的,没错。但是当 URL 不匹配时,我不是我的服务来返回不同的错误代码。因此,我在 SLIM 文档中读到 withStatus(500) 会这样做。但不确定为什么这不起作用。
  • @deceze - 我希望你明白我想说的话。我只想使用 withStatus 更改状态,这不起作用
  • 不知道为什么这不起作用,但这似乎是:return $response->withJson($error,500);
  • 另外,不要忘记回复您的回复。

标签: php slim-3


【解决方案1】:

Response-object 是不可变的,因此无法更改。 with*() 方法确实返回了 Response-object 的副本,其值已更改。

$app->get('/', function(Request $request, Response $response, $args = []) {
    $error = array('result' => false, 'message' => 'Bad Request', 'dev'=>'', 'data' => []);
    $response->write(json_encode($error)); // helper method for ->getBody()->write($val)
    return $response->withStatus(500);
});

请参阅 this answer 为什么不需要重新分配 write 上的值。

您也可以改用withJson

$app->get('/', function(Request $request, Response $response, $args = []) {
    $error = array('result' => false, 'message' => 'Bad Request', 'dev'=>'', 'data' => []);
    return $response->withJson($error, 500);
});

【讨论】:

  • 谢谢。这行得通。我以前试过这个,但似乎我说错了。 :-)
  • 嘿,我有同样的问题,但不同的是我需要在我的自定义类中进行。我如何写我的回复是 $response -> getBody() -> write(json_encode($this -> parseObject(703, 'Missing Params!')));。我想添加响应代码,但无法让它与您的答案一起使用,知道吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多