SlimFramework php v3, withStatus(500) does not wor

2019-08-03 04:25发布

问题:

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


标签: php slim-3