我正在尝试处理苗条框架自定义中间件中的错误,但不知道如何在我的代码中执行此操作我正在这样做,如果请求不是四种特定类型然后通过错误,我想在错误的哈德尔inHandler有适当的消息和状态,但目前这个代码只是在postman中返回状态,在响应正文中有一个空白屏幕。我对SLIM不太熟悉。提前致谢
<?php
require 'vendor/autoload.php';
use \Slim\App;
$c = new \Slim\Container();
$c['notAllowedHandler'] = function ($c) {
return function ($request, $response, $methods) use ($c) {
return $c['response']
->withStatus(405)
->withHeader('Allow', implode(', ', $methods))
->withHeader('Content-type', 'application/json')
->write(json_encode(array("c_status"=>"405","message"=>"Bad Request")));
};
};
$c['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['response']
->withStatus(404)
->withHeader('Content-type', 'application/json')
->write(json_encode(array("c_status"=>"404","message"=>"Not Found")));
};
};
$c['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
$data = [
'c_status' => $response->getStatus(),
'message' => $exception->getMessage()
];
return $container->get('response')->withStatus($response->getStatus())
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
$app = new App($c);
$app->add(function ($request, $response, $next) {
if($request->isGet() || $request->isPost() || $request->isPut() || $request->isDelete()){
$response = $next($request, $response);
}else{
$response = $response->withStatus(403);
}
return $response;
});
require 'API/routes.php';
$app->run();
答案 0 :(得分:1)
抛出异常:
$app->add(function ($request, $response, $next) {
if($request->isGet() || $request->isPost() || $request->isPut() || $request->isDelete()){
$response = $next($request, $response);
}else{
throw new \Exception("Forbidden", 403);
}
return $response;
})