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.

    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制