检测是否在不使用自定义异常类的情况下手动抛出异常

时间:2013-05-29 18:47:36

标签: php exception exception-handling try-catch

我的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()我手动抛出的自定义错误文本,而不是其他代码抛出的异常,因为这些可能包含敏感信息或非常技术性信息用户不应该看到。

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

2 个答案:

答案 0 :(得分:1)

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

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

然后使用getCode

答案 1 :(得分:0)

我已经考虑过这个了,我会说你正在做的事情要求自定义异常类。如果你想绕过它(最终会更加混乱),你基本上会创建一个所有异常都可以修改的全局(或同一范围)变量,并在你的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());
}

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