我有一条带有一些自定义中间件的路由,并且有一个附加到该路由的控制器。
进入控制器时,需要检查自定义对象(在请求中传递)以在需要时中止控制器操作。
public function myControllerFunction(Request $request){
...
if(isset($data["data-key"])){
abort(Response::HTTP_BAD_REQUEST, "custom abort message");
}
...
//do other call
}
启动了异常终止操作,我在日志中看到了它,并带有相应的消息,但中间件继续执行并陷入另一个错误(由于控制器异常终止,该中断在调用另一个方法之前中断)。 因此,初始响应错误消息将被覆盖。
我的目标是停止我的代码在控制器中运行,并停止在“之后”设置为«的中间件执行。我期望中止会取消所有代码执行。
我尝试使用throw Exception(…)
,但是结果是相同的,但是自定义异常没有成功。我还尝试在中间件中使用“笨拙的样式”代码(在该代码中检查请求中是否已存在错误消息或异常),但这在此位置是不正确的。
为什么中止不取消代码执行?
有关更多信息,我的路由器如下所示:
$router->post(
'path',
[
'as' => 'element.functionName',
'uses'=>'ElementResourceController@myControllerFunction',
'middleware' => [
'middleware-before-1',
'middleware-before-2',
'middleware-before-3',
'middleware-after-1',
'middleware-after-2',
'middleware-after-3'
],
]
);
我在中间件之前看起来像这样
public function handle(Request $request, Closure $next){
// do things
if(this){
//do that
}
return $next($request);
}
我的中间件之后
public function handle(Request $request, Closure $next){
$resp = $next($request);
///do things
//other error at this line, because abort in controller did not work as expected
//this middleware should not be executed
$element = Element::findOrFail($resp->getData()->key);
return $resp;
}