Question

I have just built a restful API with Slim Framework. For error conditions I simply respond with appropriate error codes for each error case and called with $app->halt, for example:

$app->halt(403, "Unauthorized");

But when I curled my API with -v and when I viewed headers in Firefox with HTTPFox I am always seeing error code 500. Anyone else notice this? Is there something I'm missing?

No correct solution

OTHER TIPS

I ran into this same issue myself recently because I had forgotten to instantiate the $app variable within my function.

If you are not explicitly stating for your function to use($app), try adding the following line before $app-halt(403, 'Unauthorized') in order to see the desired error code:

$app = Slim::getInstance();

It is not allowed to call halt() method outside of the route callback. You should use like this;

$app->get('/method/', function () {
  //logical controls
  //do something
    //or
  $app->halt();
});   

There is a difference between halt() and setStatus().

With halt(), you will stop the current script execution and render a response according to the HTTP status code and message you choose to send. You can do it anywhere in your app with this code :

$app = \Slim\Slim::getInstance(); //if you don't have access to $app
$statusCode = 403;
$body = 'Unauthorized';
$app->halt($statusCode, $body);
//App will stop immediately

With setStatus() or $this->response->status(); you will only change the HTTP status code you are sending but your app will continue to execute like normally and won't stop. Its only changing the header that Slim will send to your client at then end of the route execution.

$app = \Slim\Slim::getInstance(); //if you don't have access to $app
$statusCode = 403;
$app->response->setStatus(400);
//App will continue normally
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top