【问题标题】:Propagate exception to next catch将异常传播到下一个捕获
【发布时间】:2015-02-03 08:02:02
【问题描述】:

我有这个代码:

<?php
[...]

// Authentication error
catch(AuthException $e)
{
    // TODO: Save fault to auth into DB

    // Propagate exception
    throw $e;
}

// Common exception
catch(Exception $e)
{
    // TODO: Log error here

    $response = JsonResponse(array("error" => $e->getMessage()));
    $response->send();
}

我希望能够抛出 AuthException 和 Exception,并希望确保 AuthException 的 catch 将错误存储到 db 中,并且作为常见的 Exception 将作为错误返回。 但是现在我有错误,我有未发现的异常。 或者我可能需要在 AuthException 的构造函数中记录错误?

【问题讨论】:

  • 你在被捕获后抛出异常,所以如果你没有另一层代码可以捕获它并对其进行处理,你将有一个Uncaught exception 错误
  • 为什么不简单地在$response 的catch(AuthException $e) 块中添加一列?

标签: php exception


【解决方案1】:

你不需要捕获每个异常,我猜你想做这样的事情?

try {
      //...
} catch(Exception $e){

  if($e instanceof AuthException ) {
    // Log error here
  }

    $response = JsonResponse(array("error" => $e->getMessage()));
    $response->send();
}

【讨论】:

  • 是的,就是这样。但这种方式并不自然。因为我可以避免 AuthException,并且只需 switch/case 或类似的方法来解决一个 catch 块中的错误类型
猜你喜欢
  • 1970-01-01
  • 2011-12-14
  • 2016-08-26
  • 2012-10-22
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多