2012-11-12 10 views
6

API'mde bazı şeyler kötü giderse, bir http 500 isteği vermek istiyorum.İnce çerçeve ile http 500 dönüş

$app = new Slim(); 
$app->halt(500); 
ben bu kodu çalıştırırsanız Hala http 200

dönmek

:

$status = $app->response()->status(); 
    echo $status; //Here it is 200 
$status = $app->response()->status(500); 
    echo $status; //Here it is 500 

bir HTTP 200

cevap

6

$app->response()->status(500); doğrudur, docs bkz bana ver susturur here.

Durumu ayarladıktan sonra, $app->run(); numaralı telefonu aradığınızdan emin olun, bu işlem yanıt kodunu, üstbilgileri ve gövdeyi hazırlayacak ve çıkaracaktır.

Düzenleme, bir rota veya İnce irade çıkışı 404 yanıt tanımlamak emin olun bu çalışır:

require 'Slim/Slim.php'; 
\Slim\Slim::registerAutoloader(); 

$app = new \Slim\Slim(); 

$app->response()->status(500); 

$app->get('/', function() { 
    // index route 
}); 

$app->run(); 
+0

$ app = new Slim(); \t \t $ app-> response() -> status (500); \t \t $ app-> run(); Hala kemanda bir http 200 döndürür, ancak web görünümü artık 404'tür. Neden? – rubin

+0

HTTPLiveHeaders veya Firebug veya Chrome Dev Tools (F12) kullanarak yanıt kodunu kontrol edin. – MrCode

+0

Kemancıda ve Firebug'da http 200'ü döndürür. – rubin

2

sen> $ app- yayınlandıktan sonra() başlığı itmek varsa, her zaman can herkes hala burada bu sorun varsa

header('HTTP/1.1 401 Anonymous not allowed'); 
+0

bunu test ettiniz mi? Benim için çalışmadı. –

+0

Hayır, bazı yolları tanımladım, örneğin: $ dinlenme -> gönderi ('/ yol', işlev() kullanımı ($ dinlenme, $ değişken) { ... (bir şeyler yanlışsa) { header ('HTTP/1.1 400 JSON geçersiz'); exit(); } } – Chris

+0

Bu, Slim'in 'status()' ve 'setStatus()' durum kodunu değiştiremediğinde benim için çalıştı.Diğerleri için, PHP 5.4'ten bu yana [http_response_code] 'u (http://php.net/http_response_code) şu şekilde kullanabilirsiniz: http_response_code (500); ' – Cole

6

yaptığım sona erdi budur: başlık php fonksiyonu güvenmek

Setup bir hata işleyicisi

 

    $app->error(function (Exception $exc) use ($app) { 
     // custom exception codes used for HTTP status 
     if ($exc->getCode() !== 0) { 
      $app->response->setStatus($exc->getCode()); 
     } 

     $app->response->headers->set('Content-Type', 'application/json'); 
     echo json_encode(["error" => $exc->getMessage()]); 
    }); 

sonra, her zaman belirli bir HTTP durum durum koduyla bir özel durum atmak dönmek gerekir dahil: (İnce forumunda buldum)

 

    throw new Exception("My custom exception with status code of my choice", 401); 

0

İnce çerçeve v2 wiki status

require 'Slim/Slim.php'; 

\Slim\Slim::registerAutoloader(); 

$app = new \Slim\Slim(); 

$app->get('/', function() use ($app) { 
    $app->response()->setStatus(500); 
    $app->response()->setBody("responseText"); 
    return $app->response(); 
}); 

$app->run(); 

veya

$app->get('/', function() use ($app) { 
    $app->halt(500, "responseText"); 
});