【问题标题】:Detect if an exception has been thrown manually without using a custom exception class检测是否在不使用自定义异常类的情况下手动抛出异常
【发布时间】:2013-05-29 18:47:36
【问题描述】:

我的 php 应用程序中有一个 try-catch 块,如下所示:

try {
  if ($userForgotToEnterField) {
     throw new Exception('You need to fill in your name!');
  }
  ...
  doDifferentThingsThatCanThrowExceptions();
  ...
} catch (ExpectedException $e) {
  $template->setError('A database error occured.');
} catch (Exception $e) {
  $template->setError($e->getMessage());
}

我只想输出 $e->getMessage() 用于我手动抛出的带有自定义错误文本的异常,而不是其他代码抛出的异常,因为这些可能包含敏感信息或用户应该使用的非常技术信息没看到。

是否可以在不使用自定义异常类的情况下区分手动抛出的异常和某些方法抛出的随机异常?

【问题讨论】:

  • 我看不出有人想要这个,但你可以在抛出异常时设置一个全局变量来区分它们
  • 您可以扩展 Exceptions 类,然后捕获您的自定义 Exceptions php.net/manual/en/language.exceptions.extending.php
  • 好吧,我的项目中真的不需要自定义异常类。那我为什么要使用一个呢?这会产生不必要的复杂性。感谢您对全局变量的建议,但我认为这会造成更多的混乱。
  • 但是 OP 请求没有自定义异常(如果可能的话)
  • @Zulakis:为这个场景添加自定义异常,不会让你的代码更复杂;它相当简化了它(特别是对于其他期望它的开发人员)

标签: php exception exception-handling try-catch


【解决方案1】:

我同意最好只编写自己的异常。如果出于某种原因您不想这样做,您可以设置自定义错误消息和自定义错误代码(异常构造函数的 第二个参数。)如果错误代码是您的,请检查每个抛出的异常,并且只显示那些:

public Exception::__construct() ([ string $message = "" [,int $code = 0[, Exception $previous = NULL ]]] )

然后使用getCode

【讨论】:

    【解决方案2】:

    我已经考虑过这一点,我想说你正在做的事情确实需要一个自定义异常类。如果你想绕过它(这最终会更令人困惑),你基本上会创建一个所有异常都可以修改的全局(或相同范围)变量,并在你的 throw 块中标记它。

    $threwCustomException = false;
    
    try {
      if ($userForgotToEnterField) {
         throw new Exception('You need to fill in your name!');
         $threwCustomException = true;
      }
      ...
      doDifferentThingsThatCanThrowExceptions();
      ...
    } catch (ExpectedException $e) {
      $template->setError('A database error occured.');
    } catch (Exception $e) {
        if($threwCustomException){
            //Whatever custom exception handling you wanted here....
        }
      $template->setError($e->getMessage());
    }
    

    这是我能想到的最好的了。然而,这是一个坏主意,这就是允许您创建自己的异常类的全部原因。我知道您不是在寻找这个答案,但是由于您看起来像是在尝试不创建大量额外代码,因此我只需将 Exception 扩展为“CustomException”或特定于您的项目的其他名称,然后抛出对于所有情况,并以这种方式处理。 希望对您有所帮助。

    【讨论】:

    • class CustomException extends Exception { } 这就是我目前正在使用的 ;-) 感觉有点笨。
    • 哈哈......几年前的我在那里听到了你的声音。但如果你能从更大的角度来看,它会让代码更容易理解,因为你以相同的方式处理所有异常,未来的编码人员(包括你未来的自己)不必弄清楚这种疯狂的自定义错误处理真正的系统(除非我理解错了)与这种方法没有任何不同。另外,这更干净:) 干杯!
    猜你喜欢
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 2015-05-01
    • 2011-10-06
    • 1970-01-01
    相关资源
    最近更新 更多