PHP自定义错误处理程序:如何确定是否在try{}catch{}块中生成异常


PHP Custom Error Handler: How to determine if exception was generated within try{}catch{} block?

我有一个自定义的错误处理程序:

set_error_handler('API_Error_Handler');
register_shutdown_function('Fatal_Error_Handler'); // This one calls API_Error_Handler eventually

在下面的例子中,catch{} section和API_Error_Handler section都被执行。

try{
  // Exception raised here
} catch(Exception $e){
  // No error reporting needed, do something else
}

我想只执行catch{}。我怎么做呢?也许可以确定在API_Error_Handler内异常是否已经被try-catch捕获?或者有其他可用的方法吗?

示例代码:

set_error_handler(function() {
  echo "Error is handled by custom error handler. <br>"; 
});
try{
  new SoapClient('http://bad.address/wsdl');
} catch(Exception $e){
  echo "Error is caught. <br>";
}

我认为最好的方法是自己创建一个Exception类,扩展Exception:

class MyCustomException extends 'Exception {}

并把它扔到需要的地方。然后修改

} catch (Exception $e)

} catch (MyCustomException $e) 

,你应该只捕获你的自定义异常