Slim.php `halt` method behaves differently than do

2019-08-11 01:43发布

Slim's documentation reads the following in regard to the framework's halt method:

Halt

The Slim application’s halt() method will immediately return an HTTP response with a given status code and body. This method accepts two arguments: the HTTP status code and an optional message. Slim will immediately halt the current application and send an HTTP response to the client with the specified status and optional message (as the response body). This will override the existing \Slim\Http\Response object.

e.g.

//Send a default 500 error response
$app->halt(500);

//Or if you encounter a Balrog...
$app->halt(403, 'You shall not pass!');

Because I'm having some problems in this area, I've built the following test application, according to their documentation:

<?php

// Include Slim framework dependencies;
require '../lib/Slim/Slim.php';

\Slim\Slim::registerAutoloader(); // Slim's autloader;
$app = new \Slim\Slim();

//Send a default 500 error response
$app->halt(500);

And interestingly, the response I get is:

Fatal error: Uncaught exception 'Slim\Exception\Stop' in D:\projects\myApplication\api\lib\Slim\Slim.php:1004 Stack trace: #0 D:\projects\myApplication\api\lib\Slim\Slim.php(1024): Slim\Slim->stop() #1 D:\projects\myApplication\api\app\app.php(10): Slim\Slim->halt(500) #2 D:\projects\myApplication\api\public\index.php(4): include_once('D:\__projects\S...') #3 {main} thrown in D:\projects\myApplication\api\lib\Slim\Slim.php on line 1004

Needless the say, the HTTP response code is 200. So what's going on with Slim, exactly? Why isn't the HTTP response code 500?

标签: php http slim
1条回答
Juvenile、少年°
2楼-- · 2019-08-11 02:00

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();
});   
查看更多
登录 后发表回答