2017-06-30 21 views
1

我開始學習PHP Slim-Framework v3。但是我幾次發現它很困難。SlimFramework php v3,withStatus(500)不起作用

這裏是我的代碼:

$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.

我做錯了什麼或錯過了什麼?

我試圖調查其他問題,但我沒有找到任何幫助我的東西。

+0

除了(?):如果請求是壞的,500是錯誤的響應代碼; 400是正確的。 – deceze

+0

是的,沒錯。但是當URL不匹配時,我不是我的服務來返回不同的錯誤代碼。因此,我在SLIM文件中讀到,使用狀態(500)會做到這一點。但不知道爲什麼這不起作用。 –

+0

@deceze - 我希望你明白我想說的話。我只是想改變狀態使用withStatus,這是行不通的 –

回答

2

Response - 對象是不可變的,因此它不能更改。方法with*()確實返回Response對象的副本,其中的值已更改。

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

謝謝。這工作。我之前嘗試過,但似乎我說錯了。 :-) –

+0

嘿,我有同樣的問題,但不同的是,我需要在我的自定義類內做到這一點。我寫我的回覆是$ response - > getBody() - > write(json_encode($ this - > parseObject(703,'Missing Params!')));.我想添加響應代碼,但不能讓它與你的答案,任何想法一起工作? –