Revert http 500 with Slim framework

If something is bad in my API, I want to return an http 500 request.

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

It still returns 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 

he still gives me http 200

+6
source share
4 answers

$app->response()->status(500); true, see docs here .

Make sure you call $app->run(); after setting the status, it will prepare and display the response code, headers and body.

To change , make sure you define a route, or Slim will output a 404 answer, this works:

 require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->response()->status(500); $app->get('/', function () { // index route }); $app->run(); 
+6
source

If anyone else has this problem, here is what I did:

Error Handler Setup

     $ 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 at any time when you need to return a specific HTTP status, throw an exception with the status code turned on:

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

(found it on Slim forum)

+6
source

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

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

Slim framework v2 viking 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"); }); 
0
source

All Articles