doujiao7679 2013-05-29 18:47
浏览 262

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

I got a try-catch block in my php application like this:

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());
}

I would like to only output $e->getMessage() for the exceptions I have manually thrown with a custom error text and not the ones that have been thrown by the other code as these might contain sensitive information or very technical info that the user should not see.

Is it possible to differentiate from a manually thrown exception and a random exception thrown by some method without using a custom exception class?

  • 写回答

2条回答 默认 最新

  • 普通网友 2013-05-29 19:01
    关注

    I've thought about this a bit and I'd say that what you are doing DOES call for a custom exception class. If you want to get around it (which in the end is going to be more confusing), you would basically create a global (or same-scope) variable that all exceptions can modify, and in your throw block flag it.

    $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());
    }
    

    That's the best I can think of. However, this is a bad idea, and it's the whole reason you are allowed to create your own exception classes. I know you're not looking for this answer, but since you look like you're trying not to create a TON of extra code, I would just extend Exception to "CustomException" or some other name specific to your project, and throw that for all cases, and handle it that way. Hope that helps.

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站