我无法在PHP代码中捕获异常

Sam*_*pak 3 php exception-handling

我有以下代码:

function doSomething()
{
     try {
         doSomeNastyStuff() // throws Exception
     } catch(\Exception $e) {
         if ($this->errorHandler) {
             call_user_func($e);
         } else {
             throw($e);
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

但是,catch块不起作用.堆栈跟踪向我显示该行发生的错误doSomeNastyStuff().问题出在哪儿?

Sam*_*pak 5

问题是,你正在重新抛出你的异常.堆栈跟踪是Exception实例的一部分,此时会记录,创建异常.您可以通过获取堆栈跟踪

 $e->getTrace(); // Exception $e
Run Code Online (Sandbox Code Playgroud)

当你在你的代码中重新抛出异常时,它仍然会记录旧的堆栈跟踪,这会欺骗你的框架向你展示,异常实际发生在该行doSomeNastyStuff(),看起来它catch不起作用.

因此,最好以下列方式重新抛出异常:

/** instead of throw($e) do */
throw new \Exception("Unhandled exception", 1, $e);
Run Code Online (Sandbox Code Playgroud)

从php5.3开始,完全Exception constructor具有可选的第三个参数$previous用于此目的.然后,您可以获得之前的Exception使用$e->getPrevious();