Laravel异常处理:“错误”类的异常

时间:2014-09-14 12:57:47

标签: php exception laravel laravel-4

我使用单个Closure来处理我的应用中的异常:

App::error(function(Exception $exception, $code)
{
    if (is_a($exception, 'MsgException')) {
        ...
        return;
    }
    dd($exception); // debugging
});

奇怪的是,如果我抛出MsgException ......

<?php use MsgException; // alias for ExampleNamespace\MsgException

...
throw new MsgException();

...这是一个自定义类......

<?php namespace ExampleNamespace;

use RuntimeException;

class MsgException extends RuntimeException {}

... is_a($exception)falsedd($exception)表示它是ErrorException

我不知道为什么会这样。有关如何调试我的应用程序的任何建议或想法吗?

2 个答案:

答案 0 :(得分:1)

不要使用常规异常处理程序来处理其他类型的异常。注册你自己的。

App::error(function(ExampleNamespace\MsgException $exception, $code)
{
    dd($exception); // debugging
});

有关App::error的更多信息,请参阅here

答案 1 :(得分:0)

简而言之,答案非常简单:它无法正常工作,因为异常会在视图中抛出。 您可以通过简单添加

来测试
throw new \RuntimeException('Test');

到控制器方法或路由闭包或视图外的任何位置,并添加

<?php throw new \RuntimeException('Test'); ?>

到视图模板。 Laravel会将第一个显示为RuntimeException,将第二个显示为ErrorException

不幸的是,这并没有帮助实际解决问题。

PS:在Illuminate \ View \ Engines \ CompilerEngine中,handleViewException方法替换了原始异常:

protected function handleViewException($e, $obLevel)
{
    $e = new \ErrorException($this->getMessage($e), 0, 1, $e->getFile(), $e->getLine(), $e);

    parent::handleViewException($e, $obLevel);
}