SlimFramework php v3, withStatus(500) does not work

大兔子大兔子 提交于 2019-12-11 10:45:28

问题


I started learning PHP Slim-Framework v3. But I'm finding it difficult on few occasions.

Here is my code:

$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));
});

Now I want to respond with status 500 to the user when ever I have issues in service. But unfortunately this is not working. Though I'm getting a response, it is returning 200 status instead of 500.

Am I doing something wrong or am I missing something?

I tried looking into other issues but I did not find anything helping me out.


回答1:


The Response-object is immutable, therefore it cannot be changed. The methods with*() do return a copy of the Response-object with the changed value.

$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);
});

See this answer why you dont need to reassign the value on write.

You can also use withJson instead:

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


来源:https://stackoverflow.com/questions/44845409/slimframework-php-v3-withstatus500-does-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!