Return http 500 with Slim framework

不想你离开。 提交于 2020-01-01 09:53:06

问题


If somethings goes bad in my API i want to return a http 500 request.

$app = new Slim();
$app->halt(500);

It still return a http 200.

If i run this code:

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

it stills give me a http 200


回答1:


The $app->response()->status(500); is correct, see the docs here.

Check to make sure you're calling $app->run(); after setting the status, this will prepare and output the response code, headers and body.

Edit, make sure you define a route or Slim will output the 404 response, this works:

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

$app = new \Slim\Slim();

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

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

$app->run();



回答2:


If anyone still has this issue here is what I ended up doing:

Setup an error handler


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

then, anytime you need to return a particular HTTP status throw an Exception with the status code included:


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

(Found it on the Slim forum)




回答3:


If you have to push header after $app->run(), you can always rely on the header php function:

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



回答4:


Slim framework 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();

or

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


来源:https://stackoverflow.com/questions/13346255/return-http-500-with-slim-framework

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