我在理解Laravel如何处理异常时遇到了问题.我在global.php中注册了Exception处理程序,如下所示:
use MyNamespace\Custom\Exceptions\NotAllowedException;
App::error(function(NotAllowedException $exception, $code)
{
die("MyNamespace\Custom\Exceptions\NotAllowedException catched");
});
App::error(function(\Exception $exception)
{
echo "general exception thrown<br/>";
});
Run Code Online (Sandbox Code Playgroud)
在控制器操作中,我现在抛出一个NotAllowedException.然而,奇怪的是,第一个异常被捕获,然后是NotFoundException.
因此输出是:
general exception thrown
MyNamespace\Custom\Exceptions\NotAllowedException catched
Run Code Online (Sandbox Code Playgroud)
我认为异常处理程序堆栈因此只处理NotAllowedException.但我错了.我是否误解了Laravel中错误处理的概念,还是这种意外行为?
另一件事:我无法将http响应标头设置为401.关于此问题还有其他线程,但到目前为止还没有解决方案.如果有人对此有所了解,我将不胜感激.
谢谢你的时间和每一个回复!干杯
Der*_*ola 12
异常处理可以看作是颠倒的瀑布.首先检查定义的最后一个处理程序.举个例子:
// Custom Exception
class CustomException extends Exception {}
// Error handler in global.php
App::error(function(Exception $exception, $code)
{
echo 'Debug: Exception<br/>';
});
App::error(function(CustomException $exception, $code)
{
echo 'Debug: CustomException<br/>';
});
// Exception in routes.php (or any other place)
throw new CustomException();
Run Code Online (Sandbox Code Playgroud)
两种类型都匹配Exception类型,因此输出:Debug:CustomException Debug:Exception
但是,如果从处理程序中返回一些内容,则只触发第一个匹配的处理程序.要使用HTTP 401响应代码返回JSON响应,请执行以下操作:
App::error(function(Exception $exception, $code)
{
return Response::json(array(
'error' => 'Something went wrong (Exception)'
), 500);
});
App::error(function(NotAllowedException $exception, $code)
{
return Response::json(array(
'error' => 'Something went wrong (NotAllowedException)'
), 401);
});
Run Code Online (Sandbox Code Playgroud)
因此,通常,您希望首先定义异常处理程序.
| 归档时间: |
|
| 查看次数: |
6355 次 |
| 最近记录: |