我对PHP比较陌生,这可能是这里的主要问题——我感觉我错过了一些PHP内部的基本原理,这些基本原理要么使解决这个问题变得直截了当,要么使我明显地知道为什么我在浪费时间!…
基本上在下面的Slim API代码中,我希望由优秀的entomb/Slim -json- API中间件添加的异常处理也适用于随后的myMiddleware。如下所示,它似乎只处理路由代码中产生的故障…
(PHP v 5.4.17)
$ php composer.phar info
entomb/slim-json-api dev-master c11e001 Slim extension to implement fast JSON API's
slim/slim 2.6.2 Slim Framework, a PHP micro framework
API代码:require 'vendor/autoload.php';
use Slim'Middleware;
class myMiddleware extends Middleware
{
public function call()
{
$uri_array = explode('/', $this->app->request->getResourceUri());
$env = $this->app->environment;
if($uri_array[2] == 98) {
throw new 'Exception("User $uri_array[2], you are not even welcome in middleware!");
} else {
$body = array('user_from_middleware' => $uri_array[2]);
$env['slim.input'] = json_encode($body);
}
$this->next->call();
}
}
///////////////////////////////////////////////////////////////////////////////////
$app = new 'Slim'Slim();
$app->view(new 'JsonApiView());
$app->add(new 'JsonApiMiddleware());
$app->add(new myMiddleware());
$app->get('/user/:id', function($id) use ($app) {
if ($id == 99) {
throw new 'Exception("User $id, you are not welcome!");
} else {
$body = json_decode($app->request->getBody());
$body->msg = "User $id welcome to my API!";
$app->render(200,(array) $body);
}
});
下面是一个忽略了两个exception的请求:
$ curl http://localhost:8082/test.php/user/1
{"user_from_middleware":"1","msg":"User 1 welcome to my API!","error":false,"status":200}
…这个在路由中触发Exception,显示jsonapimmiddleware正在工作:
$ curl http://localhost:8082/test.php/user/99
{"msg":"ERROR: User 99, you are not welcome!","error":true,"status":500}
…但是当这个在myMiddleware中触发Exception时,API什么也不返回:
$ curl http://localhost:8082/test.php/user/98
$
…我可以从日志中看到异常确实被抛出了:
[Mon Nov 7 21:54:08 2016] PHP Fatal error: Uncaught exception 'Exception' with message 'User 98, you are not even welcome in middleware!' in /path/to/test.php:14
Stack trace:
#0 /path/to/vendor/slim/slim/Slim/Slim.php(1302): myMiddleware->call()
#1 /path/to/test.php(42): Slim'Slim->run()
#2 {main}
thrown in /path/to/test.php on line 14
我错过了什么?如果这是一个乏味的问题,再次道歉。
如果抛出异常,您可能不应该在MyMiddlware
中使用$this->next->call()
…
class myMiddleware extends Middleware
{
public function call()
{
$uri_array = explode('/', $this->app->request->getResourceUri());
$env = $this->app->environment;
if($uri_array[2] == 98) {
throw new 'Exception("User $uri_array[2], you are not even welcome in middleware!");
} else {
$body = array('user_from_middleware' => $uri_array[2]);
$env['slim.input'] = json_encode($body);
$this->next->call(); // call next callable only if exception was not thrown
}
}
}
看起来你在用Slim v2。,但这是我在Slim 3.5中要做的。