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


Laravel exception handling: exception with "wrong" class

我使用单个闭包来处理应用程序中的异常:

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

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

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

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

App::error的更多信息,请点击此处。

简短的回答非常简单:它不起作用,因为异常被抛在视图内。您可以通过简单添加来测试这一点

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);
}